llvm-stress.cpp 23 KB

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