• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- unittests/IR/ModuleTest.cpp - Module unit tests --------------------===//
2 //
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 #include "llvm/IR/Module.h"
11 #include "llvm/IR/GlobalVariable.h"
12 #include "llvm/Support/RandomNumberGenerator.h"
13 #include "gtest/gtest.h"
14 
15 #include <random>
16 
17 using namespace llvm;
18 
19 namespace {
20 
sortByName(const GlobalVariable & L,const GlobalVariable & R)21 bool sortByName(const GlobalVariable &L, const GlobalVariable &R) {
22   return L.getName() < R.getName();
23 }
24 
sortByNameReverse(const GlobalVariable & L,const GlobalVariable & R)25 bool sortByNameReverse(const GlobalVariable &L, const GlobalVariable &R) {
26   return sortByName(R, L);
27 }
28 
TEST(ModuleTest,sortGlobalsByName)29 TEST(ModuleTest, sortGlobalsByName) {
30   LLVMContext Context;
31   for (auto compare : {&sortByName, &sortByNameReverse}) {
32     Module M("M", Context);
33     Type *T = Type::getInt8Ty(Context);
34     GlobalValue::LinkageTypes L = GlobalValue::ExternalLinkage;
35     (void)new GlobalVariable(M, T, false, L, nullptr, "A");
36     (void)new GlobalVariable(M, T, false, L, nullptr, "F");
37     (void)new GlobalVariable(M, T, false, L, nullptr, "G");
38     (void)new GlobalVariable(M, T, false, L, nullptr, "E");
39     (void)new GlobalVariable(M, T, false, L, nullptr, "B");
40     (void)new GlobalVariable(M, T, false, L, nullptr, "H");
41     (void)new GlobalVariable(M, T, false, L, nullptr, "C");
42     (void)new GlobalVariable(M, T, false, L, nullptr, "D");
43 
44     // Sort the globals by name.
45     EXPECT_FALSE(std::is_sorted(M.global_begin(), M.global_end(), compare));
46     M.getGlobalList().sort(compare);
47     EXPECT_TRUE(std::is_sorted(M.global_begin(), M.global_end(), compare));
48   }
49 }
50 
TEST(ModuleTest,randomNumberGenerator)51 TEST(ModuleTest, randomNumberGenerator) {
52   LLVMContext Context;
53   static char ID;
54   struct DummyPass : ModulePass {
55     DummyPass() : ModulePass(ID) {}
56     bool runOnModule(Module &) { return true; }
57   } DP;
58 
59   Module M("R", Context);
60 
61   std::uniform_int_distribution<int> dist;
62   const size_t NBCheck = 10;
63 
64   std::array<int, NBCheck> RandomStreams[2];
65   for (auto &RandomStream : RandomStreams) {
66     std::unique_ptr<RandomNumberGenerator> RNG = M.createRNG(&DP);
67     std::generate(RandomStream.begin(), RandomStream.end(),
68                   [&]() { return dist(*RNG); });
69   }
70 
71   EXPECT_TRUE(std::equal(RandomStreams[0].begin(), RandomStreams[0].end(),
72                          RandomStreams[1].begin()));
73 }
74 
75 } // end namespace
76