llvm-stress.cpp 24 KB

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