1//===- llvm-stress.cpp - Generate random LL files to stress-test LLVM -----===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This program is a utility that generates random .ll files to stress-test
10// different components in LLVM.
11//
12//===----------------------------------------------------------------------===//
13
14#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"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
34#include "llvm/IR/Verifier.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FileSystem.h"
39#include "llvm/Support/InitLLVM.h"
40#include "llvm/Support/ToolOutputFile.h"
41#include "llvm/Support/WithColor.h"
42#include "llvm/Support/raw_ostream.h"
43#include <cassert>
44#include <cstddef>
45#include <cstdint>
46#include <memory>
47#include <string>
48#include <system_error>
49#include <vector>
50
51namespace llvm {
52
53static cl::OptionCategory StressCategory("Stress Options");
54
55static cl::opt<unsigned> SeedCL("seed", cl::desc("Seed used for randomness"),
56 cl::init(Val: 0), cl::cat(StressCategory));
57
58static cl::opt<unsigned> SizeCL(
59 "size",
60 cl::desc("The estimated size of the generated function (# of instrs)"),
61 cl::init(Val: 100), cl::cat(StressCategory));
62
63static cl::opt<std::string> OutputFilename("o",
64 cl::desc("Override output filename"),
65 cl::value_desc("filename"),
66 cl::cat(StressCategory));
67
68static cl::list<StringRef> AdditionalScalarTypes(
69 "types", cl::CommaSeparated,
70 cl::desc("Additional IR scalar types "
71 "(always includes i1, i8, i16, i32, i64, float and double)"));
72
73static cl::opt<bool> EnableScalableVectors(
74 "enable-scalable-vectors",
75 cl::desc("Generate IR involving scalable vector types"),
76 cl::init(Val: false), cl::cat(StressCategory));
77
78
79namespace {
80
81/// 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) {}
89
90 /// Return a random integer, up to a
91 /// maximum of 2**19 - 1.
92 uint32_t Rand() {
93 uint32_t Val = Seed + 0x000b07a1;
94 Seed = (Val * 0x3c7c0ac1);
95 // Only lowest 19 bits are random-ish.
96 return Seed & 0x7ffff;
97 }
98
99 /// Return a random 64 bit integer.
100 uint64_t Rand64() {
101 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;
106 }
107
108 /// Rand operator for STL algorithms.
109 ptrdiff_t operator()(ptrdiff_t y) {
110 return Rand64() % y;
111 }
112
113 /// Make this like a C++11 random device
114 using result_type = uint32_t ;
115
116 static constexpr result_type min() { return 0; }
117 static constexpr result_type max() { return 0x7ffff; }
118
119 uint32_t operator()() {
120 uint32_t Val = Rand();
121 assert(Val <= max() && "Random value out of range");
122 return Val;
123 }
124
125private:
126 unsigned Seed;
127};
128
129/// Generate an empty function with a default argument list.
130Function *GenEmptyFunction(Module *M) {
131 // Define a few arguments
132 LLVMContext &Context = M->getContext();
133 Type* ArgsTy[] = {
134 PointerType::get(C&: Context, AddressSpace: 0),
135 PointerType::get(C&: Context, AddressSpace: 0),
136 PointerType::get(C&: Context, AddressSpace: 0),
137 Type::getInt32Ty(C&: Context),
138 Type::getInt64Ty(C&: Context),
139 Type::getInt8Ty(C&: Context)
140 };
141
142 auto *FuncTy = FunctionType::get(Result: Type::getVoidTy(C&: Context), Params: ArgsTy, isVarArg: false);
143 // Pick a unique name to describe the input parameters
144 Twine Name = "autogen_SD" + Twine{SeedCL};
145 auto *Func = Function::Create(Ty: FuncTy, Linkage: GlobalValue::ExternalLinkage, N: Name, M);
146 Func->setCallingConv(CallingConv::C);
147 return Func;
148}
149
150/// A base class, implementing utilities needed for
151/// modifying and adding new random instructions.
152struct Modifier {
153 /// Used to store the randomly generated values.
154 using PieceTable = std::vector<Value *>;
155
156public:
157 /// C'tor
158 Modifier(BasicBlock *Block, PieceTable *PT, Random *R)
159 : BB(Block), PT(PT), Ran(R), Context(BB->getContext()) {
160 ScalarTypes.assign(l: {Type::getInt1Ty(C&: Context), Type::getInt8Ty(C&: Context),
161 Type::getInt16Ty(C&: Context), Type::getInt32Ty(C&: Context),
162 Type::getInt64Ty(C&: Context), Type::getFloatTy(C&: Context),
163 Type::getDoubleTy(C&: Context)});
164
165 for (auto &Arg : AdditionalScalarTypes) {
166 Type *Ty = nullptr;
167 if (Arg == "half")
168 Ty = Type::getHalfTy(C&: Context);
169 else if (Arg == "fp128")
170 Ty = Type::getFP128Ty(C&: Context);
171 else if (Arg == "x86_fp80")
172 Ty = Type::getX86_FP80Ty(C&: Context);
173 else if (Arg == "ppc_fp128")
174 Ty = Type::getPPC_FP128Ty(C&: Context);
175 else if (Arg.starts_with(Prefix: "i")) {
176 unsigned N = 0;
177 Arg.drop_front().getAsInteger(Radix: 10, Result&: N);
178 if (N > 0)
179 Ty = Type::getIntNTy(C&: Context, N);
180 }
181 if (!Ty) {
182 errs() << "Invalid IR scalar type: '" << Arg << "'!\n";
183 exit(status: 1);
184 }
185
186 ScalarTypes.push_back(x: Ty);
187 }
188 }
189
190 /// virtual D'tor to silence warnings.
191 virtual ~Modifier() = default;
192
193 /// Add a new instruction.
194 virtual void Act() = 0;
195
196 /// Add N new instructions,
197 virtual void ActN(unsigned n) {
198 for (unsigned i=0; i<n; ++i)
199 Act();
200 }
201
202protected:
203 /// Return a random integer.
204 uint32_t getRandom() {
205 return Ran->Rand();
206 }
207
208 /// Return a random value from the list of known values.
209 Value *getRandomVal() {
210 assert(PT->size());
211 return PT->at(n: getRandom() % PT->size());
212 }
213
214 Constant *getRandomConstant(Type *Tp) {
215 if (Tp->isIntegerTy()) {
216 if (getRandom() & 1)
217 return ConstantInt::getAllOnesValue(Ty: Tp);
218 return ConstantInt::getNullValue(Ty: Tp);
219 } else if (Tp->isFloatingPointTy()) {
220 if (getRandom() & 1)
221 return ConstantFP::getAllOnesValue(Ty: Tp);
222 return ConstantFP::getZero(Ty: Tp);
223 }
224 return UndefValue::get(T: Tp);
225 }
226
227 /// Return a random value with a known type.
228 Value *getRandomValue(Type *Tp) {
229 unsigned index = getRandom();
230 for (unsigned i=0; i<PT->size(); ++i) {
231 Value *V = PT->at(n: (index + i) % PT->size());
232 if (V->getType() == Tp)
233 return V;
234 }
235
236 // If the requested type was not found, generate a constant value.
237 if (Tp->isIntegerTy()) {
238 if (getRandom() & 1)
239 return ConstantInt::getAllOnesValue(Ty: Tp);
240 return ConstantInt::getNullValue(Ty: Tp);
241 } else if (Tp->isFloatingPointTy()) {
242 if (getRandom() & 1)
243 return ConstantFP::getAllOnesValue(Ty: Tp);
244 return ConstantFP::getZero(Ty: Tp);
245 } else if (auto *VTp = dyn_cast<FixedVectorType>(Val: Tp)) {
246 std::vector<Constant*> TempValues;
247 TempValues.reserve(n: VTp->getNumElements());
248 for (unsigned i = 0; i < VTp->getNumElements(); ++i)
249 TempValues.push_back(x: getRandomConstant(Tp: VTp->getScalarType()));
250
251 ArrayRef<Constant*> VectorValue(TempValues);
252 return ConstantVector::get(V: VectorValue);
253 }
254
255 return UndefValue::get(T: Tp);
256 }
257
258 /// Return a random value of any pointer type.
259 Value *getRandomPointerValue() {
260 unsigned index = getRandom();
261 for (unsigned i=0; i<PT->size(); ++i) {
262 Value *V = PT->at(n: (index + i) % PT->size());
263 if (V->getType()->isPointerTy())
264 return V;
265 }
266 return UndefValue::get(T: PointerType::get(C&: Context, AddressSpace: 0));
267 }
268
269 /// Return a random value of any vector type.
270 Value *getRandomVectorValue() {
271 unsigned index = getRandom();
272 for (unsigned i=0; i<PT->size(); ++i) {
273 Value *V = PT->at(n: (index + i) % PT->size());
274 if (V->getType()->isVectorTy())
275 return V;
276 }
277 return UndefValue::get(T: pickVectorType());
278 }
279
280 /// Pick a random type.
281 Type *pickType() {
282 return (getRandom() & 1) ? pickVectorType() : pickScalarType();
283 }
284
285 /// Pick a random vector type.
286 Type *pickVectorType(VectorType *VTy = nullptr) {
287
288 Type *Ty = pickScalarType();
289
290 if (VTy)
291 return VectorType::get(ElementType: Ty, EC: VTy->getElementCount());
292
293 // Select either fixed length or scalable vectors with 50% probability
294 // (only if scalable vectors are enabled)
295 bool Scalable = EnableScalableVectors && getRandom() & 1;
296
297 // Pick a random vector width in the range 2**0 to 2**4.
298 // by adding two randoms we are generating a normal-like distribution
299 // around 2**3.
300 unsigned width = 1<<((getRandom() % 3) + (getRandom() % 3));
301 return VectorType::get(ElementType: Ty, NumElements: width, Scalable);
302 }
303
304 /// Pick a random scalar type.
305 Type *pickScalarType() {
306 return ScalarTypes[getRandom() % ScalarTypes.size()];
307 }
308
309 /// Basic block to populate
310 BasicBlock *BB;
311
312 /// Value table
313 PieceTable *PT;
314
315 /// Random number generator
316 Random *Ran;
317
318 /// Context
319 LLVMContext &Context;
320
321 std::vector<Type *> ScalarTypes;
322};
323
324struct LoadModifier: public Modifier {
325 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R)
326 : Modifier(BB, PT, R) {}
327
328 void Act() override {
329 // Try to use predefined pointers. If non-exist, use undef pointer value;
330 Value *Ptr = getRandomPointerValue();
331 Type *Ty = pickType();
332 Value *V = new LoadInst(Ty, Ptr, "L", BB->getTerminator()->getIterator());
333 PT->push_back(x: V);
334 }
335};
336
337struct StoreModifier: public Modifier {
338 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R)
339 : Modifier(BB, PT, R) {}
340
341 void Act() override {
342 // Try to use predefined pointers. If non-exist, use undef pointer value;
343 Value *Ptr = getRandomPointerValue();
344 Type *ValTy = pickType();
345
346 // Do not store vectors of i1s because they are unsupported
347 // by the codegen.
348 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
349 return;
350
351 Value *Val = getRandomValue(Tp: ValTy);
352 new StoreInst(Val, Ptr, BB->getTerminator()->getIterator());
353 }
354};
355
356struct BinModifier: public Modifier {
357 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R)
358 : Modifier(BB, PT, R) {}
359
360 void Act() override {
361 Value *Val0 = getRandomVal();
362 Value *Val1 = getRandomValue(Tp: Val0->getType());
363
364 // Don't handle pointer types.
365 if (Val0->getType()->isPointerTy() ||
366 Val1->getType()->isPointerTy())
367 return;
368
369 // Don't handle i1 types.
370 if (Val0->getType()->getScalarSizeInBits() == 1)
371 return;
372
373 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
374 Instruction* Term = BB->getTerminator();
375 unsigned R = getRandom() % (isFloat ? 7 : 13);
376 Instruction::BinaryOps Op;
377
378 switch (R) {
379 default: llvm_unreachable("Invalid BinOp");
380 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
381 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
382 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
383 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
384 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
385 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
386 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
387 case 7: {Op = Instruction::Shl; break; }
388 case 8: {Op = Instruction::LShr; break; }
389 case 9: {Op = Instruction::AShr; break; }
390 case 10:{Op = Instruction::And; break; }
391 case 11:{Op = Instruction::Or; break; }
392 case 12:{Op = Instruction::Xor; break; }
393 }
394
395 PT->push_back(
396 x: BinaryOperator::Create(Op, S1: Val0, S2: Val1, Name: "B", InsertBefore: Term->getIterator()));
397 }
398};
399
400/// Generate constant values.
401struct ConstModifier: public Modifier {
402 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R)
403 : Modifier(BB, PT, R) {}
404
405 void Act() override {
406 Type *Ty = pickType();
407
408 if (Ty->isVectorTy()) {
409 switch (getRandom() % 2) {
410 case 0: if (Ty->isIntOrIntVectorTy())
411 return PT->push_back(x: ConstantVector::getAllOnesValue(Ty));
412 break;
413 case 1: if (Ty->isIntOrIntVectorTy())
414 return PT->push_back(x: ConstantVector::getNullValue(Ty));
415 }
416 }
417
418 if (Ty->isFloatingPointTy()) {
419 // Generate 128 random bits, the size of the (currently)
420 // largest floating-point types.
421 uint64_t RandomBits[2];
422 for (unsigned i = 0; i < 2; ++i)
423 RandomBits[i] = Ran->Rand64();
424
425 APInt RandomInt(Ty->getPrimitiveSizeInBits(), ArrayRef(RandomBits));
426 APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
427
428 if (getRandom() & 1)
429 return PT->push_back(x: ConstantFP::getZero(Ty));
430 return PT->push_back(x: ConstantFP::get(Context&: Ty->getContext(), V: RandomFloat));
431 }
432
433 if (Ty->isIntegerTy()) {
434 switch (getRandom() % 7) {
435 case 0:
436 return PT->push_back(x: ConstantInt::get(
437 Ty, V: APInt::getAllOnes(numBits: Ty->getPrimitiveSizeInBits())));
438 case 1:
439 return PT->push_back(
440 x: ConstantInt::get(Ty, V: APInt::getZero(numBits: Ty->getPrimitiveSizeInBits())));
441 case 2:
442 case 3:
443 case 4:
444 case 5:
445 case 6:
446 PT->push_back(x: ConstantInt::get(Ty, V: getRandom(), /*IsSigned=*/false,
447 /*ImplicitTrunc=*/true));
448 }
449 }
450 }
451};
452
453struct AllocaModifier: public Modifier {
454 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R)
455 : Modifier(BB, PT, R) {}
456
457 void Act() override {
458 Type *Tp = pickType();
459 const DataLayout &DL = BB->getDataLayout();
460 PT->push_back(x: new AllocaInst(Tp, DL.getAllocaAddrSpace(), "A",
461 BB->getFirstNonPHIIt()));
462 }
463};
464
465struct ExtractElementModifier: public Modifier {
466 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
467 : Modifier(BB, PT, R) {}
468
469 void Act() override {
470 Value *Val0 = getRandomVectorValue();
471 Value *V = ExtractElementInst::Create(
472 Vec: Val0, Idx: getRandomValue(Tp: Type::getInt32Ty(C&: BB->getContext())), NameStr: "E",
473 InsertBefore: BB->getTerminator()->getIterator());
474 return PT->push_back(x: V);
475 }
476};
477
478struct ShuffModifier: public Modifier {
479 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R)
480 : Modifier(BB, PT, R) {}
481
482 void Act() override {
483 Value *Val0 = getRandomVectorValue();
484 Value *Val1 = getRandomValue(Tp: Val0->getType());
485
486 // Can't express arbitrary shufflevectors for scalable vectors
487 if (isa<ScalableVectorType>(Val: Val0->getType()))
488 return;
489
490 unsigned Width = cast<FixedVectorType>(Val: Val0->getType())->getNumElements();
491 std::vector<Constant*> Idxs;
492
493 Type *I32 = Type::getInt32Ty(C&: BB->getContext());
494 for (unsigned i=0; i<Width; ++i) {
495 Constant *CI = ConstantInt::get(Ty: I32, V: getRandom() % (Width*2));
496 // Pick some undef values.
497 if (!(getRandom() % 5))
498 CI = UndefValue::get(T: I32);
499 Idxs.push_back(x: CI);
500 }
501
502 Constant *Mask = ConstantVector::get(V: Idxs);
503
504 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
505 BB->getTerminator()->getIterator());
506 PT->push_back(x: V);
507 }
508};
509
510struct InsertElementModifier: public Modifier {
511 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
512 : Modifier(BB, PT, R) {}
513
514 void Act() override {
515 Value *Val0 = getRandomVectorValue();
516 Value *Val1 = getRandomValue(Tp: Val0->getType()->getScalarType());
517
518 Value *V = InsertElementInst::Create(
519 Vec: Val0, NewElt: Val1, Idx: getRandomValue(Tp: Type::getInt32Ty(C&: BB->getContext())), NameStr: "I",
520 InsertBefore: BB->getTerminator()->getIterator());
521 return PT->push_back(x: V);
522 }
523};
524
525struct CastModifier: public Modifier {
526 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R)
527 : Modifier(BB, PT, R) {}
528
529 void Act() override {
530 Value *V = getRandomVal();
531 Type *VTy = V->getType();
532 Type *DestTy = pickScalarType();
533
534 // Handle vector casts vectors.
535 if (VTy->isVectorTy())
536 DestTy = pickVectorType(VTy: cast<VectorType>(Val: VTy));
537
538 // no need to cast.
539 if (VTy == DestTy) return;
540
541 // Pointers:
542 if (VTy->isPointerTy()) {
543 if (!DestTy->isPointerTy())
544 DestTy = PointerType::get(C&: Context, AddressSpace: 0);
545 return PT->push_back(
546 x: new BitCastInst(V, DestTy, "PC", BB->getTerminator()->getIterator()));
547 }
548
549 unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
550 unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
551
552 // Generate lots of bitcasts.
553 if ((getRandom() & 1) && VSize == DestSize) {
554 return PT->push_back(
555 x: new BitCastInst(V, DestTy, "BC", BB->getTerminator()->getIterator()));
556 }
557
558 // Both types are integers:
559 if (VTy->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy()) {
560 if (VSize > DestSize) {
561 return PT->push_back(
562 x: new TruncInst(V, DestTy, "Tr", BB->getTerminator()->getIterator()));
563 } else {
564 assert(VSize < DestSize && "Different int types with the same size?");
565 if (getRandom() & 1)
566 return PT->push_back(x: new ZExtInst(
567 V, DestTy, "ZE", BB->getTerminator()->getIterator()));
568 return PT->push_back(
569 x: new SExtInst(V, DestTy, "Se", BB->getTerminator()->getIterator()));
570 }
571 }
572
573 // Fp to int.
574 if (VTy->isFPOrFPVectorTy() && DestTy->isIntOrIntVectorTy()) {
575 if (getRandom() & 1)
576 return PT->push_back(x: new FPToSIInst(
577 V, DestTy, "FC", BB->getTerminator()->getIterator()));
578 return PT->push_back(
579 x: new FPToUIInst(V, DestTy, "FC", BB->getTerminator()->getIterator()));
580 }
581
582 // Int to fp.
583 if (VTy->isIntOrIntVectorTy() && DestTy->isFPOrFPVectorTy()) {
584 if (getRandom() & 1)
585 return PT->push_back(x: new SIToFPInst(
586 V, DestTy, "FC", BB->getTerminator()->getIterator()));
587 return PT->push_back(
588 x: new UIToFPInst(V, DestTy, "FC", BB->getTerminator()->getIterator()));
589 }
590
591 // Both floats.
592 if (VTy->isFPOrFPVectorTy() && DestTy->isFPOrFPVectorTy()) {
593 if (VSize > DestSize) {
594 return PT->push_back(x: new FPTruncInst(
595 V, DestTy, "Tr", BB->getTerminator()->getIterator()));
596 } else if (VSize < DestSize) {
597 return PT->push_back(
598 x: new FPExtInst(V, DestTy, "ZE", BB->getTerminator()->getIterator()));
599 }
600 // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
601 // for which there is no defined conversion. So do nothing.
602 }
603 }
604};
605
606struct SelectModifier: public Modifier {
607 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R)
608 : Modifier(BB, PT, R) {}
609
610 void Act() override {
611 // Try a bunch of different select configuration until a valid one is found.
612 Value *Val0 = getRandomVal();
613 Value *Val1 = getRandomValue(Tp: Val0->getType());
614
615 Type *CondTy = Type::getInt1Ty(C&: Context);
616
617 // If the value type is a vector, and we allow vector select, then in 50%
618 // of the cases generate a vector select.
619 if (auto *VTy = dyn_cast<VectorType>(Val: Val0->getType()))
620 if (getRandom() & 1)
621 CondTy = VectorType::get(ElementType: CondTy, EC: VTy->getElementCount());
622
623 Value *Cond = getRandomValue(Tp: CondTy);
624 Value *V = SelectInst::Create(C: Cond, S1: Val0, S2: Val1, NameStr: "Sl",
625 InsertBefore: BB->getTerminator()->getIterator());
626 return PT->push_back(x: V);
627 }
628};
629
630struct CmpModifier: public Modifier {
631 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R)
632 : Modifier(BB, PT, R) {}
633
634 void Act() override {
635 Value *Val0 = getRandomVal();
636 Value *Val1 = getRandomValue(Tp: Val0->getType());
637
638 if (Val0->getType()->isPointerTy()) return;
639 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
640
641 int op;
642 if (fp) {
643 op = getRandom() %
644 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
645 CmpInst::FIRST_FCMP_PREDICATE;
646 } else {
647 op = getRandom() %
648 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
649 CmpInst::FIRST_ICMP_PREDICATE;
650 }
651
652 Value *V = CmpInst::Create(Op: fp ? Instruction::FCmp : Instruction::ICmp,
653 Pred: (CmpInst::Predicate)op, S1: Val0, S2: Val1, Name: "Cmp",
654 InsertBefore: BB->getTerminator()->getIterator());
655 return PT->push_back(x: V);
656 }
657};
658
659} // end anonymous namespace
660
661static void FillFunction(Function *F, Random &R) {
662 // Create a legal entry block.
663 BasicBlock *BB = BasicBlock::Create(Context&: F->getContext(), Name: "BB", Parent: F);
664 ReturnInst::Create(C&: F->getContext(), InsertAtEnd: BB);
665
666 // Create the value table.
667 Modifier::PieceTable PT;
668
669 // Consider arguments as legal values.
670 for (auto &arg : F->args())
671 PT.push_back(x: &arg);
672
673 // List of modifiers which add new random instructions.
674 std::vector<std::unique_ptr<Modifier>> Modifiers;
675 Modifiers.emplace_back(args: new LoadModifier(BB, &PT, &R));
676 Modifiers.emplace_back(args: new StoreModifier(BB, &PT, &R));
677 auto SM = Modifiers.back().get();
678 Modifiers.emplace_back(args: new ExtractElementModifier(BB, &PT, &R));
679 Modifiers.emplace_back(args: new ShuffModifier(BB, &PT, &R));
680 Modifiers.emplace_back(args: new InsertElementModifier(BB, &PT, &R));
681 Modifiers.emplace_back(args: new BinModifier(BB, &PT, &R));
682 Modifiers.emplace_back(args: new CastModifier(BB, &PT, &R));
683 Modifiers.emplace_back(args: new SelectModifier(BB, &PT, &R));
684 Modifiers.emplace_back(args: new CmpModifier(BB, &PT, &R));
685
686 // Generate the random instructions
687 AllocaModifier{BB, &PT, &R}.ActN(n: 5); // Throw in a few allocas
688 ConstModifier{BB, &PT, &R}.ActN(n: 40); // Throw in a few constants
689
690 for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
691 for (auto &Mod : Modifiers)
692 Mod->Act();
693
694 SM->ActN(n: 5); // Throw in a few stores.
695}
696
697static void IntroduceControlFlow(Function *F, Random &R) {
698 std::vector<Instruction*> BoolInst;
699 for (auto &Instr : F->front()) {
700 if (Instr.getType() == IntegerType::getInt1Ty(C&: F->getContext()))
701 BoolInst.push_back(x: &Instr);
702 }
703
704 llvm::shuffle(first: BoolInst.begin(), last: BoolInst.end(), g&: R);
705
706 for (auto *Instr : BoolInst) {
707 BasicBlock *Curr = Instr->getParent();
708 BasicBlock::iterator Loc = Instr->getIterator();
709 BasicBlock *Next = Curr->splitBasicBlock(I: Loc, BBName: "CF");
710 Instr->moveBefore(InsertPos: Curr->getTerminator()->getIterator());
711 if (Curr != &F->getEntryBlock()) {
712 BranchInst::Create(IfTrue: Curr, IfFalse: Next, Cond: Instr,
713 InsertBefore: Curr->getTerminator()->getIterator());
714 Curr->getTerminator()->eraseFromParent();
715 }
716 }
717}
718
719} // end namespace llvm
720
721int main(int argc, char **argv) {
722 using namespace llvm;
723
724 InitLLVM X(argc, argv);
725 cl::HideUnrelatedOptions(Categories: {&StressCategory, &getColorCategory()});
726 cl::ParseCommandLineOptions(argc, argv, Overview: "llvm codegen stress-tester\n");
727
728 LLVMContext Context;
729 auto M = std::make_unique<Module>(args: "/tmp/autogen.bc", args&: Context);
730 Function *F = GenEmptyFunction(M: M.get());
731
732 // Pick an initial seed value
733 Random R(SeedCL);
734 // Generate lots of random instructions inside a single basic block.
735 FillFunction(F, R);
736 // Break the basic block into many loops.
737 IntroduceControlFlow(F, R);
738
739 // Figure out what stream we are supposed to write to...
740 std::unique_ptr<ToolOutputFile> Out;
741 // Default to standard output.
742 if (OutputFilename.empty())
743 OutputFilename = "-";
744
745 std::error_code EC;
746 Out.reset(p: new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
747 if (EC) {
748 errs() << EC.message() << '\n';
749 return 1;
750 }
751
752 // Check that the generated module is accepted by the verifier.
753 if (verifyModule(M: *M.get(), OS: &Out->os()))
754 report_fatal_error(reason: "Broken module found, compilation aborted!");
755
756 // Output textual IR.
757 M->print(OS&: Out->os(), AAW: nullptr);
758
759 Out->keep();
760
761 return 0;
762}
763