1 //===- llvm/unittest/IR/ConstantsTest.cpp - Constants unit tests ----------===//
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 #include "llvm/IR/Constants.h"
10 #include "llvm-c/Core.h"
11 #include "llvm/AsmParser/Parser.h"
12 #include "llvm/IR/DerivedTypes.h"
13 #include "llvm/IR/InstrTypes.h"
14 #include "llvm/IR/Instruction.h"
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Support/SourceMgr.h"
18 #include "gtest/gtest.h"
19 
20 namespace llvm {
21 namespace {
22 
23 TEST(ConstantsTest, Integer_i1) {
24   LLVMContext Context;
25   IntegerType *Int1 = IntegerType::get(Context, 1);
26   Constant *One = ConstantInt::get(Int1, 1, true);
27   Constant *Zero = ConstantInt::get(Int1, 0);
28   Constant *NegOne = ConstantInt::get(Int1, static_cast<uint64_t>(-1), true);
29   EXPECT_EQ(NegOne, ConstantInt::getSigned(Int1, -1));
30   Constant *Poison = PoisonValue::get(Int1);
31 
32   // Input:  @b = constant i1 add(i1 1 , i1 1)
33   // Output: @b = constant i1 false
34   EXPECT_EQ(Zero, ConstantExpr::getAdd(One, One));
35 
36   // @c = constant i1 add(i1 -1, i1 1)
37   // @c = constant i1 false
38   EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, One));
39 
40   // @d = constant i1 add(i1 -1, i1 -1)
41   // @d = constant i1 false
42   EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, NegOne));
43 
44   // @e = constant i1 sub(i1 -1, i1 1)
45   // @e = constant i1 false
46   EXPECT_EQ(Zero, ConstantExpr::getSub(NegOne, One));
47 
48   // @f = constant i1 sub(i1 1 , i1 -1)
49   // @f = constant i1 false
50   EXPECT_EQ(Zero, ConstantExpr::getSub(One, NegOne));
51 
52   // @g = constant i1 sub(i1 1 , i1 1)
53   // @g = constant i1 false
54   EXPECT_EQ(Zero, ConstantExpr::getSub(One, One));
55 
56   // @h = constant i1 shl(i1 1 , i1 1)  ; poison
57   // @h = constant i1 poison
58   EXPECT_EQ(Poison, ConstantExpr::getShl(One, One));
59 
60   // @i = constant i1 shl(i1 1 , i1 0)
61   // @i = constant i1 true
62   EXPECT_EQ(One, ConstantExpr::getShl(One, Zero));
63 
64   // @j = constant i1 lshr(i1 1, i1 1)  ; poison
65   // @j = constant i1 poison
66   EXPECT_EQ(Poison, ConstantExpr::getLShr(One, One));
67 
68   // @m = constant i1 ashr(i1 1, i1 1)  ; poison
69   // @m = constant i1 poison
70   EXPECT_EQ(Poison, ConstantExpr::getAShr(One, One));
71 
72   // @n = constant i1 mul(i1 -1, i1 1)
73   // @n = constant i1 true
74   EXPECT_EQ(One, ConstantExpr::getMul(NegOne, One));
75 
76   // @o = constant i1 sdiv(i1 -1, i1 1) ; overflow
77   // @o = constant i1 true
78   EXPECT_EQ(One, ConstantExpr::getSDiv(NegOne, One));
79 
80   // @p = constant i1 sdiv(i1 1 , i1 -1); overflow
81   // @p = constant i1 true
82   EXPECT_EQ(One, ConstantExpr::getSDiv(One, NegOne));
83 
84   // @q = constant i1 udiv(i1 -1, i1 1)
85   // @q = constant i1 true
86   EXPECT_EQ(One, ConstantExpr::getUDiv(NegOne, One));
87 
88   // @r = constant i1 udiv(i1 1, i1 -1)
89   // @r = constant i1 true
90   EXPECT_EQ(One, ConstantExpr::getUDiv(One, NegOne));
91 
92   // @s = constant i1 srem(i1 -1, i1 1) ; overflow
93   // @s = constant i1 false
94   EXPECT_EQ(Zero, ConstantExpr::getSRem(NegOne, One));
95 
96   // @t = constant i1 urem(i1 -1, i1 1)
97   // @t = constant i1 false
98   EXPECT_EQ(Zero, ConstantExpr::getURem(NegOne, One));
99 
100   // @u = constant i1 srem(i1  1, i1 -1) ; overflow
101   // @u = constant i1 false
102   EXPECT_EQ(Zero, ConstantExpr::getSRem(One, NegOne));
103 }
104 
105 TEST(ConstantsTest, IntSigns) {
106   LLVMContext Context;
107   IntegerType *Int8Ty = Type::getInt8Ty(Context);
108   EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, false)->getSExtValue());
109   EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, true)->getSExtValue());
110   EXPECT_EQ(100, ConstantInt::getSigned(Int8Ty, 100)->getSExtValue());
111   EXPECT_EQ(-50, ConstantInt::get(Int8Ty, 206)->getSExtValue());
112   EXPECT_EQ(-50, ConstantInt::getSigned(Int8Ty, -50)->getSExtValue());
113   EXPECT_EQ(206U, ConstantInt::getSigned(Int8Ty, -50)->getZExtValue());
114 
115   // Overflow is handled by truncation.
116   EXPECT_EQ(0x3b, ConstantInt::get(Int8Ty, 0x13b)->getSExtValue());
117 }
118 
119 TEST(ConstantsTest, FP128Test) {
120   LLVMContext Context;
121   Type *FP128Ty = Type::getFP128Ty(Context);
122 
123   IntegerType *Int128Ty = Type::getIntNTy(Context, 128);
124   Constant *Zero128 = Constant::getNullValue(Int128Ty);
125   Constant *X = ConstantExpr::getUIToFP(Zero128, FP128Ty);
126   EXPECT_TRUE(isa<ConstantFP>(X));
127 }
128 
129 TEST(ConstantsTest, PointerCast) {
130   LLVMContext C;
131   Type *Int8PtrTy = Type::getInt8PtrTy(C);
132   Type *Int32PtrTy = Type::getInt32PtrTy(C);
133   Type *Int64Ty = Type::getInt64Ty(C);
134   VectorType *Int8PtrVecTy = FixedVectorType::get(Int8PtrTy, 4);
135   VectorType *Int32PtrVecTy = FixedVectorType::get(Int32PtrTy, 4);
136   VectorType *Int64VecTy = FixedVectorType::get(Int64Ty, 4);
137   VectorType *Int8PtrScalableVecTy = ScalableVectorType::get(Int8PtrTy, 4);
138   VectorType *Int32PtrScalableVecTy = ScalableVectorType::get(Int32PtrTy, 4);
139   VectorType *Int64ScalableVecTy = ScalableVectorType::get(Int64Ty, 4);
140 
141   // ptrtoint i8* to i64
142   EXPECT_EQ(
143       Constant::getNullValue(Int64Ty),
144       ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrTy), Int64Ty));
145 
146   // bitcast i8* to i32*
147   EXPECT_EQ(Constant::getNullValue(Int32PtrTy),
148             ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrTy),
149                                          Int32PtrTy));
150 
151   // ptrtoint <4 x i8*> to <4 x i64>
152   EXPECT_EQ(Constant::getNullValue(Int64VecTy),
153             ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrVecTy),
154                                          Int64VecTy));
155 
156   // ptrtoint <vscale x 4 x i8*> to <vscale x 4 x i64>
157   EXPECT_EQ(
158       Constant::getNullValue(Int64ScalableVecTy),
159       ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrScalableVecTy),
160                                    Int64ScalableVecTy));
161 
162   // bitcast <4 x i8*> to <4 x i32*>
163   EXPECT_EQ(Constant::getNullValue(Int32PtrVecTy),
164             ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrVecTy),
165                                          Int32PtrVecTy));
166 
167   // bitcast <vscale x 4 x i8*> to <vscale x 4 x i32*>
168   EXPECT_EQ(
169       Constant::getNullValue(Int32PtrScalableVecTy),
170       ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrScalableVecTy),
171                                    Int32PtrScalableVecTy));
172 
173   Type *Int32Ptr1Ty = Type::getInt32PtrTy(C, 1);
174   ConstantInt *K = ConstantInt::get(Type::getInt64Ty(C), 1234);
175 
176   // Make sure that addrspacecast of inttoptr is not folded away.
177   EXPECT_NE(K, ConstantExpr::getAddrSpaceCast(
178                    ConstantExpr::getIntToPtr(K, Int32PtrTy), Int32Ptr1Ty));
179   EXPECT_NE(K, ConstantExpr::getAddrSpaceCast(
180                    ConstantExpr::getIntToPtr(K, Int32Ptr1Ty), Int32PtrTy));
181 
182   Constant *NullInt32Ptr0 = Constant::getNullValue(Int32PtrTy);
183   Constant *NullInt32Ptr1 = Constant::getNullValue(Int32Ptr1Ty);
184 
185   // Make sure that addrspacecast of null is not folded away.
186   EXPECT_NE(Constant::getNullValue(Int32PtrTy),
187             ConstantExpr::getAddrSpaceCast(NullInt32Ptr0, Int32Ptr1Ty));
188 
189   EXPECT_NE(Constant::getNullValue(Int32Ptr1Ty),
190             ConstantExpr::getAddrSpaceCast(NullInt32Ptr1, Int32PtrTy));
191 }
192 
193 #define CHECK(x, y)                                                            \
194   {                                                                            \
195     std::string __s;                                                           \
196     raw_string_ostream __o(__s);                                               \
197     Instruction *__I = cast<ConstantExpr>(x)->getAsInstruction();              \
198     __I->print(__o);                                                           \
199     __I->deleteValue();                                                        \
200     __o.flush();                                                               \
201     EXPECT_EQ(std::string("  <badref> = " y), __s);                            \
202   }
203 
204 TEST(ConstantsTest, AsInstructionsTest) {
205   LLVMContext Context;
206   std::unique_ptr<Module> M(new Module("MyModule", Context));
207 
208   Type *Int64Ty = Type::getInt64Ty(Context);
209   Type *Int32Ty = Type::getInt32Ty(Context);
210   Type *Int16Ty = Type::getInt16Ty(Context);
211   Type *Int1Ty = Type::getInt1Ty(Context);
212   Type *FloatTy = Type::getFloatTy(Context);
213   Type *DoubleTy = Type::getDoubleTy(Context);
214 
215   Constant *Global =
216       M->getOrInsertGlobal("dummy", PointerType::getUnqual(Int32Ty));
217   Constant *Global2 =
218       M->getOrInsertGlobal("dummy2", PointerType::getUnqual(Int32Ty));
219 
220   Constant *P0 = ConstantExpr::getPtrToInt(Global, Int32Ty);
221   Constant *P1 = ConstantExpr::getUIToFP(P0, FloatTy);
222   Constant *P2 = ConstantExpr::getUIToFP(P0, DoubleTy);
223   Constant *P3 = ConstantExpr::getTrunc(P0, Int1Ty);
224   Constant *P4 = ConstantExpr::getPtrToInt(Global2, Int32Ty);
225   Constant *P5 = ConstantExpr::getUIToFP(P4, FloatTy);
226   Constant *P6 = ConstantExpr::getBitCast(P4, FixedVectorType::get(Int16Ty, 2));
227 
228   Constant *One = ConstantInt::get(Int32Ty, 1);
229   Constant *Two = ConstantInt::get(Int64Ty, 2);
230   Constant *Big = ConstantInt::get(Context, APInt{256, uint64_t(-1), true});
231   Constant *Elt = ConstantInt::get(Int16Ty, 2015);
232   Constant *Poison16 = PoisonValue::get(Int16Ty);
233   Constant *Undef64 = UndefValue::get(Int64Ty);
234   Constant *PoisonV16 = PoisonValue::get(P6->getType());
235 
236 #define P0STR "ptrtoint (ptr @dummy to i32)"
237 #define P1STR "uitofp (i32 ptrtoint (ptr @dummy to i32) to float)"
238 #define P2STR "uitofp (i32 ptrtoint (ptr @dummy to i32) to double)"
239 #define P3STR "ptrtoint (ptr @dummy to i1)"
240 #define P4STR "ptrtoint (ptr @dummy2 to i32)"
241 #define P5STR "uitofp (i32 ptrtoint (ptr @dummy2 to i32) to float)"
242 #define P6STR "bitcast (i32 ptrtoint (ptr @dummy2 to i32) to <2 x i16>)"
243 
244   CHECK(ConstantExpr::getNeg(P0), "sub i32 0, " P0STR);
245   CHECK(ConstantExpr::getFNeg(P1), "fneg float " P1STR);
246   CHECK(ConstantExpr::getNot(P0), "xor i32 " P0STR ", -1");
247   CHECK(ConstantExpr::getAdd(P0, P0), "add i32 " P0STR ", " P0STR);
248   CHECK(ConstantExpr::getAdd(P0, P0, false, true),
249         "add nsw i32 " P0STR ", " P0STR);
250   CHECK(ConstantExpr::getAdd(P0, P0, true, true),
251         "add nuw nsw i32 " P0STR ", " P0STR);
252   CHECK(ConstantExpr::getFAdd(P1, P1), "fadd float " P1STR ", " P1STR);
253   CHECK(ConstantExpr::getSub(P0, P0), "sub i32 " P0STR ", " P0STR);
254   CHECK(ConstantExpr::getFSub(P1, P1), "fsub float " P1STR ", " P1STR);
255   CHECK(ConstantExpr::getMul(P0, P0), "mul i32 " P0STR ", " P0STR);
256   CHECK(ConstantExpr::getFMul(P1, P1), "fmul float " P1STR ", " P1STR);
257   CHECK(ConstantExpr::getUDiv(P0, P0), "udiv i32 " P0STR ", " P0STR);
258   CHECK(ConstantExpr::getSDiv(P0, P0), "sdiv i32 " P0STR ", " P0STR);
259   CHECK(ConstantExpr::getFDiv(P1, P1), "fdiv float " P1STR ", " P1STR);
260   CHECK(ConstantExpr::getURem(P0, P0), "urem i32 " P0STR ", " P0STR);
261   CHECK(ConstantExpr::getSRem(P0, P0), "srem i32 " P0STR ", " P0STR);
262   CHECK(ConstantExpr::getFRem(P1, P1), "frem float " P1STR ", " P1STR);
263   CHECK(ConstantExpr::getAnd(P0, P0), "and i32 " P0STR ", " P0STR);
264   CHECK(ConstantExpr::getOr(P0, P0), "or i32 " P0STR ", " P0STR);
265   CHECK(ConstantExpr::getXor(P0, P0), "xor i32 " P0STR ", " P0STR);
266   CHECK(ConstantExpr::getShl(P0, P0), "shl i32 " P0STR ", " P0STR);
267   CHECK(ConstantExpr::getShl(P0, P0, true), "shl nuw i32 " P0STR ", " P0STR);
268   CHECK(ConstantExpr::getShl(P0, P0, false, true),
269         "shl nsw i32 " P0STR ", " P0STR);
270   CHECK(ConstantExpr::getLShr(P0, P0, false), "lshr i32 " P0STR ", " P0STR);
271   CHECK(ConstantExpr::getLShr(P0, P0, true),
272         "lshr exact i32 " P0STR ", " P0STR);
273   CHECK(ConstantExpr::getAShr(P0, P0, false), "ashr i32 " P0STR ", " P0STR);
274   CHECK(ConstantExpr::getAShr(P0, P0, true),
275         "ashr exact i32 " P0STR ", " P0STR);
276 
277   CHECK(ConstantExpr::getSExt(P0, Int64Ty), "sext i32 " P0STR " to i64");
278   CHECK(ConstantExpr::getZExt(P0, Int64Ty), "zext i32 " P0STR " to i64");
279   CHECK(ConstantExpr::getFPTrunc(P2, FloatTy),
280         "fptrunc double " P2STR " to float");
281   CHECK(ConstantExpr::getFPExtend(P1, DoubleTy),
282         "fpext float " P1STR " to double");
283 
284   CHECK(ConstantExpr::getExactUDiv(P0, P0), "udiv exact i32 " P0STR ", " P0STR);
285 
286   CHECK(ConstantExpr::getSelect(P3, P0, P4),
287         "select i1 " P3STR ", i32 " P0STR ", i32 " P4STR);
288   CHECK(ConstantExpr::getICmp(CmpInst::ICMP_EQ, P0, P4),
289         "icmp eq i32 " P0STR ", " P4STR);
290   CHECK(ConstantExpr::getFCmp(CmpInst::FCMP_ULT, P1, P5),
291         "fcmp ult float " P1STR ", " P5STR);
292 
293   std::vector<Constant *> V;
294   V.push_back(One);
295   // FIXME: getGetElementPtr() actually creates an inbounds ConstantGEP,
296   //        not a normal one!
297   // CHECK(ConstantExpr::getGetElementPtr(Global, V, false),
298   //      "getelementptr i32*, i32** @dummy, i32 1");
299   CHECK(ConstantExpr::getInBoundsGetElementPtr(PointerType::getUnqual(Int32Ty),
300                                                Global, V),
301         "getelementptr inbounds ptr, ptr @dummy, i32 1");
302 
303   CHECK(ConstantExpr::getExtractElement(P6, One),
304         "extractelement <2 x i16> " P6STR ", i32 1");
305 
306   EXPECT_EQ(Poison16, ConstantExpr::getExtractElement(P6, Two));
307   EXPECT_EQ(Poison16, ConstantExpr::getExtractElement(P6, Big));
308   EXPECT_EQ(Poison16, ConstantExpr::getExtractElement(P6, Undef64));
309 
310   EXPECT_EQ(Elt, ConstantExpr::getExtractElement(
311                  ConstantExpr::getInsertElement(P6, Elt, One), One));
312   EXPECT_EQ(PoisonV16, ConstantExpr::getInsertElement(P6, Elt, Two));
313   EXPECT_EQ(PoisonV16, ConstantExpr::getInsertElement(P6, Elt, Big));
314   EXPECT_EQ(PoisonV16, ConstantExpr::getInsertElement(P6, Elt, Undef64));
315 }
316 
317 #ifdef GTEST_HAS_DEATH_TEST
318 #ifndef NDEBUG
319 TEST(ConstantsTest, ReplaceWithConstantTest) {
320   LLVMContext Context;
321   std::unique_ptr<Module> M(new Module("MyModule", Context));
322 
323   Type *Int32Ty = Type::getInt32Ty(Context);
324   Constant *One = ConstantInt::get(Int32Ty, 1);
325 
326   Constant *Global =
327       M->getOrInsertGlobal("dummy", PointerType::getUnqual(Int32Ty));
328   Constant *GEP = ConstantExpr::getGetElementPtr(
329       PointerType::getUnqual(Int32Ty), Global, One);
330   EXPECT_DEATH(Global->replaceAllUsesWith(GEP),
331                "this->replaceAllUsesWith\\(expr\\(this\\)\\) is NOT valid!");
332 }
333 
334 #endif
335 #endif
336 
337 #undef CHECK
338 
339 TEST(ConstantsTest, ConstantArrayReplaceWithConstant) {
340   LLVMContext Context;
341   std::unique_ptr<Module> M(new Module("MyModule", Context));
342 
343   Type *IntTy = Type::getInt8Ty(Context);
344   ArrayType *ArrayTy = ArrayType::get(IntTy, 2);
345   Constant *A01Vals[2] = {ConstantInt::get(IntTy, 0),
346                           ConstantInt::get(IntTy, 1)};
347   Constant *A01 = ConstantArray::get(ArrayTy, A01Vals);
348 
349   Constant *Global = new GlobalVariable(*M, IntTy, false,
350                                         GlobalValue::ExternalLinkage, nullptr);
351   Constant *GlobalInt = ConstantExpr::getPtrToInt(Global, IntTy);
352   Constant *A0GVals[2] = {ConstantInt::get(IntTy, 0), GlobalInt};
353   Constant *A0G = ConstantArray::get(ArrayTy, A0GVals);
354   ASSERT_NE(A01, A0G);
355 
356   GlobalVariable *RefArray =
357       new GlobalVariable(*M, ArrayTy, false, GlobalValue::ExternalLinkage, A0G);
358   ASSERT_EQ(A0G, RefArray->getInitializer());
359 
360   GlobalInt->replaceAllUsesWith(ConstantInt::get(IntTy, 1));
361   ASSERT_EQ(A01, RefArray->getInitializer());
362 }
363 
364 TEST(ConstantsTest, ConstantExprReplaceWithConstant) {
365   LLVMContext Context;
366   std::unique_ptr<Module> M(new Module("MyModule", Context));
367 
368   Type *IntTy = Type::getInt8Ty(Context);
369   Constant *G1 = new GlobalVariable(*M, IntTy, false,
370                                     GlobalValue::ExternalLinkage, nullptr);
371   Constant *G2 = new GlobalVariable(*M, IntTy, false,
372                                     GlobalValue::ExternalLinkage, nullptr);
373   ASSERT_NE(G1, G2);
374 
375   Constant *Int1 = ConstantExpr::getPtrToInt(G1, IntTy);
376   Constant *Int2 = ConstantExpr::getPtrToInt(G2, IntTy);
377   ASSERT_NE(Int1, Int2);
378 
379   GlobalVariable *Ref =
380       new GlobalVariable(*M, IntTy, false, GlobalValue::ExternalLinkage, Int1);
381   ASSERT_EQ(Int1, Ref->getInitializer());
382 
383   G1->replaceAllUsesWith(G2);
384   ASSERT_EQ(Int2, Ref->getInitializer());
385 }
386 
387 TEST(ConstantsTest, GEPReplaceWithConstant) {
388   LLVMContext Context;
389   std::unique_ptr<Module> M(new Module("MyModule", Context));
390 
391   Type *IntTy = Type::getInt32Ty(Context);
392   Type *PtrTy = PointerType::get(IntTy, 0);
393   auto *C1 = ConstantInt::get(IntTy, 1);
394   auto *Placeholder = new GlobalVariable(
395       *M, IntTy, false, GlobalValue::ExternalWeakLinkage, nullptr);
396   auto *GEP = ConstantExpr::getGetElementPtr(IntTy, Placeholder, C1);
397   ASSERT_EQ(GEP->getOperand(0), Placeholder);
398 
399   auto *Ref =
400       new GlobalVariable(*M, PtrTy, false, GlobalValue::ExternalLinkage, GEP);
401   ASSERT_EQ(GEP, Ref->getInitializer());
402 
403   auto *Global = new GlobalVariable(*M, IntTy, false,
404                                     GlobalValue::ExternalLinkage, nullptr);
405   auto *Alias = GlobalAlias::create(IntTy, 0, GlobalValue::ExternalLinkage,
406                                     "alias", Global, M.get());
407   Placeholder->replaceAllUsesWith(Alias);
408   ASSERT_EQ(GEP, Ref->getInitializer());
409   ASSERT_EQ(GEP->getOperand(0), Alias);
410 }
411 
412 TEST(ConstantsTest, AliasCAPI) {
413   LLVMContext Context;
414   SMDiagnostic Error;
415   std::unique_ptr<Module> M =
416       parseAssemblyString("@g = global i32 42", Error, Context);
417   GlobalVariable *G = M->getGlobalVariable("g");
418   Type *I16Ty = Type::getInt16Ty(Context);
419   Type *I16PTy = PointerType::get(I16Ty, 0);
420   Constant *Aliasee = ConstantExpr::getBitCast(G, I16PTy);
421   LLVMValueRef AliasRef =
422       LLVMAddAlias2(wrap(M.get()), wrap(I16Ty), 0, wrap(Aliasee), "a");
423   ASSERT_EQ(unwrap<GlobalAlias>(AliasRef)->getAliasee(), Aliasee);
424 }
425 
426 static std::string getNameOfType(Type *T) {
427   std::string S;
428   raw_string_ostream RSOS(S);
429   T->print(RSOS);
430   return S;
431 }
432 
433 TEST(ConstantsTest, BuildConstantDataArrays) {
434   LLVMContext Context;
435 
436   for (Type *T : {Type::getInt8Ty(Context), Type::getInt16Ty(Context),
437                   Type::getInt32Ty(Context), Type::getInt64Ty(Context)}) {
438     ArrayType *ArrayTy = ArrayType::get(T, 2);
439     Constant *Vals[] = {ConstantInt::get(T, 0), ConstantInt::get(T, 1)};
440     Constant *CA = ConstantArray::get(ArrayTy, Vals);
441     ASSERT_TRUE(isa<ConstantDataArray>(CA)) << " T = " << getNameOfType(T);
442     auto *CDA = cast<ConstantDataArray>(CA);
443     Constant *CA2 = ConstantDataArray::getRaw(
444         CDA->getRawDataValues(), CDA->getNumElements(), CDA->getElementType());
445     ASSERT_TRUE(CA == CA2) << " T = " << getNameOfType(T);
446   }
447 
448   for (Type *T : {Type::getHalfTy(Context), Type::getBFloatTy(Context),
449                   Type::getFloatTy(Context), Type::getDoubleTy(Context)}) {
450     ArrayType *ArrayTy = ArrayType::get(T, 2);
451     Constant *Vals[] = {ConstantFP::get(T, 0), ConstantFP::get(T, 1)};
452     Constant *CA = ConstantArray::get(ArrayTy, Vals);
453     ASSERT_TRUE(isa<ConstantDataArray>(CA)) << " T = " << getNameOfType(T);
454     auto *CDA = cast<ConstantDataArray>(CA);
455     Constant *CA2 = ConstantDataArray::getRaw(
456         CDA->getRawDataValues(), CDA->getNumElements(), CDA->getElementType());
457     ASSERT_TRUE(CA == CA2) << " T = " << getNameOfType(T);
458   }
459 }
460 
461 TEST(ConstantsTest, BuildConstantDataVectors) {
462   LLVMContext Context;
463 
464   for (Type *T : {Type::getInt8Ty(Context), Type::getInt16Ty(Context),
465                   Type::getInt32Ty(Context), Type::getInt64Ty(Context)}) {
466     Constant *Vals[] = {ConstantInt::get(T, 0), ConstantInt::get(T, 1)};
467     Constant *CV = ConstantVector::get(Vals);
468     ASSERT_TRUE(isa<ConstantDataVector>(CV)) << " T = " << getNameOfType(T);
469     auto *CDV = cast<ConstantDataVector>(CV);
470     Constant *CV2 = ConstantDataVector::getRaw(
471         CDV->getRawDataValues(), CDV->getNumElements(), CDV->getElementType());
472     ASSERT_TRUE(CV == CV2) << " T = " << getNameOfType(T);
473   }
474 
475   for (Type *T : {Type::getHalfTy(Context), Type::getBFloatTy(Context),
476                   Type::getFloatTy(Context), Type::getDoubleTy(Context)}) {
477     Constant *Vals[] = {ConstantFP::get(T, 0), ConstantFP::get(T, 1)};
478     Constant *CV = ConstantVector::get(Vals);
479     ASSERT_TRUE(isa<ConstantDataVector>(CV)) << " T = " << getNameOfType(T);
480     auto *CDV = cast<ConstantDataVector>(CV);
481     Constant *CV2 = ConstantDataVector::getRaw(
482         CDV->getRawDataValues(), CDV->getNumElements(), CDV->getElementType());
483     ASSERT_TRUE(CV == CV2) << " T = " << getNameOfType(T);
484   }
485 }
486 
487 void bitcastToGEPHelper(bool useOpaquePointers) {
488   LLVMContext Context;
489   Context.setOpaquePointers(useOpaquePointers);
490   std::unique_ptr<Module> M(new Module("MyModule", Context));
491 
492   auto *i32 = Type::getInt32Ty(Context);
493   auto *U = StructType::create(Context, "Unsized");
494   Type *EltTys[] = {i32, U};
495   auto *S = StructType::create(EltTys);
496 
497   auto *G =
498       new GlobalVariable(*M, S, false, GlobalValue::ExternalLinkage, nullptr);
499   auto *PtrTy = PointerType::get(i32, 0);
500   auto *C = ConstantExpr::getBitCast(G, PtrTy);
501   if (Context.supportsTypedPointers()) {
502     EXPECT_EQ(cast<ConstantExpr>(C)->getOpcode(), Instruction::BitCast);
503   } else {
504     /* With opaque pointers, no cast is necessary. */
505     EXPECT_EQ(C, G);
506   }
507 }
508 
509 TEST(ConstantsTest, BitcastToGEP) {
510   bitcastToGEPHelper(true);
511   bitcastToGEPHelper(false);
512 }
513 
514 bool foldFuncPtrAndConstToNull(LLVMContext &Context, Module *TheModule,
515                                uint64_t AndValue,
516                                MaybeAlign FunctionAlign = llvm::None) {
517   Type *VoidType(Type::getVoidTy(Context));
518   FunctionType *FuncType(FunctionType::get(VoidType, false));
519   Function *Func(
520       Function::Create(FuncType, GlobalValue::ExternalLinkage, "", TheModule));
521 
522   if (FunctionAlign)
523     Func->setAlignment(*FunctionAlign);
524 
525   IntegerType *ConstantIntType(Type::getInt32Ty(Context));
526   ConstantInt *TheConstant(ConstantInt::get(ConstantIntType, AndValue));
527 
528   Constant *TheConstantExpr(ConstantExpr::getPtrToInt(Func, ConstantIntType));
529 
530   bool Result =
531       ConstantExpr::get(Instruction::And, TheConstantExpr, TheConstant)
532           ->isNullValue();
533 
534   if (!TheModule) {
535     // If the Module exists then it will delete the Function.
536     delete Func;
537   }
538 
539   return Result;
540 }
541 
542 TEST(ConstantsTest, FoldFunctionPtrAlignUnknownAnd2) {
543   LLVMContext Context;
544   Module TheModule("TestModule", Context);
545   // When the DataLayout doesn't specify a function pointer alignment we
546   // assume in this case that it is 4 byte aligned. This is a bug but we can't
547   // fix it directly because it causes a code size regression on X86.
548   // FIXME: This test should be changed once existing targets have
549   // appropriate defaults. See associated FIXME in ConstantFoldBinaryInstruction
550   ASSERT_TRUE(foldFuncPtrAndConstToNull(Context, &TheModule, 2));
551 }
552 
553 TEST(ConstantsTest, DontFoldFunctionPtrAlignUnknownAnd4) {
554   LLVMContext Context;
555   Module TheModule("TestModule", Context);
556   ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, &TheModule, 4));
557 }
558 
559 TEST(ConstantsTest, FoldFunctionPtrAlign4) {
560   LLVMContext Context;
561   Module TheModule("TestModule", Context);
562   const char *AlignmentStrings[] = {"Fi32", "Fn32"};
563 
564   for (unsigned AndValue = 1; AndValue <= 2; ++AndValue) {
565     for (const char *AlignmentString : AlignmentStrings) {
566       TheModule.setDataLayout(AlignmentString);
567       ASSERT_TRUE(foldFuncPtrAndConstToNull(Context, &TheModule, AndValue));
568     }
569   }
570 }
571 
572 TEST(ConstantsTest, DontFoldFunctionPtrAlign1) {
573   LLVMContext Context;
574   Module TheModule("TestModule", Context);
575   const char *AlignmentStrings[] = {"Fi8", "Fn8"};
576 
577   for (const char *AlignmentString : AlignmentStrings) {
578     TheModule.setDataLayout(AlignmentString);
579     ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, &TheModule, 2));
580   }
581 }
582 
583 TEST(ConstantsTest, FoldFunctionAlign4PtrAlignMultiple) {
584   LLVMContext Context;
585   Module TheModule("TestModule", Context);
586   TheModule.setDataLayout("Fn8");
587   ASSERT_TRUE(foldFuncPtrAndConstToNull(Context, &TheModule, 2, Align(4)));
588 }
589 
590 TEST(ConstantsTest, DontFoldFunctionAlign4PtrAlignIndependent) {
591   LLVMContext Context;
592   Module TheModule("TestModule", Context);
593   TheModule.setDataLayout("Fi8");
594   ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, &TheModule, 2, Align(4)));
595 }
596 
597 TEST(ConstantsTest, DontFoldFunctionPtrIfNoModule) {
598   LLVMContext Context;
599   // Even though the function is explicitly 4 byte aligned, in the absence of a
600   // DataLayout we can't assume that the function pointer is aligned.
601   ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, nullptr, 2, Align(4)));
602 }
603 
604 TEST(ConstantsTest, FoldGlobalVariablePtr) {
605   LLVMContext Context;
606 
607   IntegerType *IntType(Type::getInt32Ty(Context));
608 
609   std::unique_ptr<GlobalVariable> Global(
610       new GlobalVariable(IntType, true, GlobalValue::ExternalLinkage));
611 
612   Global->setAlignment(Align(4));
613 
614   ConstantInt *TheConstant(ConstantInt::get(IntType, 2));
615 
616   Constant *TheConstantExpr(ConstantExpr::getPtrToInt(Global.get(), IntType));
617 
618   ASSERT_TRUE(ConstantExpr::get(Instruction::And, TheConstantExpr, TheConstant)
619                   ->isNullValue());
620 }
621 
622 // Check that containsUndefOrPoisonElement and containsPoisonElement is working
623 // great
624 
625 TEST(ConstantsTest, containsUndefElemTest) {
626   LLVMContext Context;
627 
628   Type *Int32Ty = Type::getInt32Ty(Context);
629   Constant *CU = UndefValue::get(Int32Ty);
630   Constant *CP = PoisonValue::get(Int32Ty);
631   Constant *C1 = ConstantInt::get(Int32Ty, 1);
632   Constant *C2 = ConstantInt::get(Int32Ty, 2);
633 
634   {
635     Constant *V1 = ConstantVector::get({C1, C2});
636     EXPECT_FALSE(V1->containsUndefOrPoisonElement());
637     EXPECT_FALSE(V1->containsPoisonElement());
638   }
639 
640   {
641     Constant *V2 = ConstantVector::get({C1, CU});
642     EXPECT_TRUE(V2->containsUndefOrPoisonElement());
643     EXPECT_FALSE(V2->containsPoisonElement());
644   }
645 
646   {
647     Constant *V3 = ConstantVector::get({C1, CP});
648     EXPECT_TRUE(V3->containsUndefOrPoisonElement());
649     EXPECT_TRUE(V3->containsPoisonElement());
650   }
651 
652   {
653     Constant *V4 = ConstantVector::get({CU, CP});
654     EXPECT_TRUE(V4->containsUndefOrPoisonElement());
655     EXPECT_TRUE(V4->containsPoisonElement());
656   }
657 }
658 
659 // Check that undefined elements in vector constants are matched
660 // correctly for both integer and floating-point types. Just don't
661 // crash on vectors of pointers (could be handled?).
662 
663 TEST(ConstantsTest, isElementWiseEqual) {
664   LLVMContext Context;
665 
666   Type *Int32Ty = Type::getInt32Ty(Context);
667   Constant *CU = UndefValue::get(Int32Ty);
668   Constant *C1 = ConstantInt::get(Int32Ty, 1);
669   Constant *C2 = ConstantInt::get(Int32Ty, 2);
670 
671   Constant *C1211 = ConstantVector::get({C1, C2, C1, C1});
672   Constant *C12U1 = ConstantVector::get({C1, C2, CU, C1});
673   Constant *C12U2 = ConstantVector::get({C1, C2, CU, C2});
674   Constant *C12U21 = ConstantVector::get({C1, C2, CU, C2, C1});
675 
676   EXPECT_TRUE(C1211->isElementWiseEqual(C12U1));
677   EXPECT_TRUE(C12U1->isElementWiseEqual(C1211));
678   EXPECT_FALSE(C12U2->isElementWiseEqual(C12U1));
679   EXPECT_FALSE(C12U1->isElementWiseEqual(C12U2));
680   EXPECT_FALSE(C12U21->isElementWiseEqual(C12U2));
681 
682   Type *FltTy = Type::getFloatTy(Context);
683   Constant *CFU = UndefValue::get(FltTy);
684   Constant *CF1 = ConstantFP::get(FltTy, 1.0);
685   Constant *CF2 = ConstantFP::get(FltTy, 2.0);
686 
687   Constant *CF1211 = ConstantVector::get({CF1, CF2, CF1, CF1});
688   Constant *CF12U1 = ConstantVector::get({CF1, CF2, CFU, CF1});
689   Constant *CF12U2 = ConstantVector::get({CF1, CF2, CFU, CF2});
690   Constant *CFUU1U = ConstantVector::get({CFU, CFU, CF1, CFU});
691 
692   EXPECT_TRUE(CF1211->isElementWiseEqual(CF12U1));
693   EXPECT_TRUE(CF12U1->isElementWiseEqual(CF1211));
694   EXPECT_TRUE(CFUU1U->isElementWiseEqual(CF12U1));
695   EXPECT_FALSE(CF12U2->isElementWiseEqual(CF12U1));
696   EXPECT_FALSE(CF12U1->isElementWiseEqual(CF12U2));
697 
698   PointerType *PtrTy = Type::getInt8PtrTy(Context);
699   Constant *CPU = UndefValue::get(PtrTy);
700   Constant *CP0 = ConstantPointerNull::get(PtrTy);
701 
702   Constant *CP0000 = ConstantVector::get({CP0, CP0, CP0, CP0});
703   Constant *CP00U0 = ConstantVector::get({CP0, CP0, CPU, CP0});
704   Constant *CP00U = ConstantVector::get({CP0, CP0, CPU});
705 
706   EXPECT_FALSE(CP0000->isElementWiseEqual(CP00U0));
707   EXPECT_FALSE(CP00U0->isElementWiseEqual(CP0000));
708   EXPECT_FALSE(CP0000->isElementWiseEqual(CP00U));
709   EXPECT_FALSE(CP00U->isElementWiseEqual(CP00U0));
710 }
711 
712 // Check that vector/aggregate constants correctly store undef and poison
713 // elements.
714 
715 TEST(ConstantsTest, CheckElementWiseUndefPoison) {
716   LLVMContext Context;
717 
718   Type *Int32Ty = Type::getInt32Ty(Context);
719   StructType *STy = StructType::get(Int32Ty, Int32Ty);
720   ArrayType *ATy = ArrayType::get(Int32Ty, 2);
721   Constant *CU = UndefValue::get(Int32Ty);
722   Constant *CP = PoisonValue::get(Int32Ty);
723 
724   {
725     Constant *CUU = ConstantVector::get({CU, CU});
726     Constant *CPP = ConstantVector::get({CP, CP});
727     Constant *CUP = ConstantVector::get({CU, CP});
728     Constant *CPU = ConstantVector::get({CP, CU});
729     EXPECT_EQ(CUU, UndefValue::get(CUU->getType()));
730     EXPECT_EQ(CPP, PoisonValue::get(CPP->getType()));
731     EXPECT_NE(CUP, UndefValue::get(CUP->getType()));
732     EXPECT_NE(CPU, UndefValue::get(CPU->getType()));
733   }
734 
735   {
736     Constant *CUU = ConstantStruct::get(STy, {CU, CU});
737     Constant *CPP = ConstantStruct::get(STy, {CP, CP});
738     Constant *CUP = ConstantStruct::get(STy, {CU, CP});
739     Constant *CPU = ConstantStruct::get(STy, {CP, CU});
740     EXPECT_EQ(CUU, UndefValue::get(CUU->getType()));
741     EXPECT_EQ(CPP, PoisonValue::get(CPP->getType()));
742     EXPECT_NE(CUP, UndefValue::get(CUP->getType()));
743     EXPECT_NE(CPU, UndefValue::get(CPU->getType()));
744   }
745 
746   {
747     Constant *CUU = ConstantArray::get(ATy, {CU, CU});
748     Constant *CPP = ConstantArray::get(ATy, {CP, CP});
749     Constant *CUP = ConstantArray::get(ATy, {CU, CP});
750     Constant *CPU = ConstantArray::get(ATy, {CP, CU});
751     EXPECT_EQ(CUU, UndefValue::get(CUU->getType()));
752     EXPECT_EQ(CPP, PoisonValue::get(CPP->getType()));
753     EXPECT_NE(CUP, UndefValue::get(CUP->getType()));
754     EXPECT_NE(CPU, UndefValue::get(CPU->getType()));
755   }
756 }
757 
758 TEST(ConstantsTest, GetSplatValueRoundTrip) {
759   LLVMContext Context;
760 
761   Type *FloatTy = Type::getFloatTy(Context);
762   Type *Int32Ty = Type::getInt32Ty(Context);
763   Type *Int8Ty = Type::getInt8Ty(Context);
764 
765   for (unsigned Min : {1, 2, 8}) {
766     auto ScalableEC = ElementCount::getScalable(Min);
767     auto FixedEC = ElementCount::getFixed(Min);
768 
769     for (auto EC : {ScalableEC, FixedEC}) {
770       for (auto *Ty : {FloatTy, Int32Ty, Int8Ty}) {
771         Constant *Zero = Constant::getNullValue(Ty);
772         Constant *One = Constant::getAllOnesValue(Ty);
773 
774         for (auto *C : {Zero, One}) {
775           Constant *Splat = ConstantVector::getSplat(EC, C);
776           ASSERT_NE(nullptr, Splat);
777 
778           Constant *SplatVal = Splat->getSplatValue();
779           EXPECT_NE(nullptr, SplatVal);
780           EXPECT_EQ(SplatVal, C);
781         }
782       }
783     }
784   }
785 }
786 
787 TEST(ConstantsTest, ComdatUserTracking) {
788   LLVMContext Context;
789   Module M("MyModule", Context);
790 
791   Comdat *C = M.getOrInsertComdat("comdat");
792   const SmallPtrSetImpl<GlobalObject *> &Users = C->getUsers();
793   EXPECT_TRUE(Users.size() == 0);
794 
795   Type *Ty = Type::getInt8Ty(Context);
796   GlobalVariable *GV1 = cast<GlobalVariable>(M.getOrInsertGlobal("gv1", Ty));
797   GV1->setComdat(C);
798   EXPECT_TRUE(Users.size() == 1);
799   EXPECT_TRUE(Users.contains(GV1));
800 
801   GlobalVariable *GV2 = cast<GlobalVariable>(M.getOrInsertGlobal("gv2", Ty));
802   GV2->setComdat(C);
803   EXPECT_TRUE(Users.size() == 2);
804   EXPECT_TRUE(Users.contains(GV2));
805 
806   GV1->eraseFromParent();
807   EXPECT_TRUE(Users.size() == 1);
808   EXPECT_TRUE(Users.contains(GV2));
809 
810   GV2->eraseFromParent();
811   EXPECT_TRUE(Users.size() == 0);
812 }
813 
814 } // end anonymous namespace
815 } // end namespace llvm
816