Constants.h 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/Constants.h - Constant class subclass definitions --*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// @file
  15. /// This file contains the declarations for the subclasses of Constant,
  16. /// which represent the different flavors of constant values that live in LLVM.
  17. /// Note that Constants are immutable (once created they never change) and are
  18. /// fully shared by structural equivalence. This means that two structurally
  19. /// equivalent constants will always have the same address. Constants are
  20. /// created on demand as needed and never deleted: thus clients don't have to
  21. /// worry about the lifetime of the objects.
  22. //
  23. //===----------------------------------------------------------------------===//
  24. #ifndef LLVM_IR_CONSTANTS_H
  25. #define LLVM_IR_CONSTANTS_H
  26. #include "llvm/ADT/APFloat.h"
  27. #include "llvm/ADT/APInt.h"
  28. #include "llvm/ADT/ArrayRef.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/StringRef.h"
  31. #include "llvm/IR/Constant.h"
  32. #include "llvm/IR/DerivedTypes.h"
  33. #include "llvm/IR/OperandTraits.h"
  34. #include "llvm/IR/User.h"
  35. #include "llvm/IR/Value.h"
  36. #include "llvm/Support/Casting.h"
  37. #include "llvm/Support/Compiler.h"
  38. #include "llvm/Support/ErrorHandling.h"
  39. #include <cassert>
  40. #include <cstddef>
  41. #include <cstdint>
  42. #include <optional>
  43. namespace llvm {
  44. template <class ConstantClass> struct ConstantAggrKeyType;
  45. /// Base class for constants with no operands.
  46. ///
  47. /// These constants have no operands; they represent their data directly.
  48. /// Since they can be in use by unrelated modules (and are never based on
  49. /// GlobalValues), it never makes sense to RAUW them.
  50. class ConstantData : public Constant {
  51. friend class Constant;
  52. Value *handleOperandChangeImpl(Value *From, Value *To) {
  53. llvm_unreachable("Constant data does not have operands!");
  54. }
  55. protected:
  56. explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {}
  57. void *operator new(size_t S) { return User::operator new(S, 0); }
  58. public:
  59. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  60. ConstantData(const ConstantData &) = delete;
  61. /// Methods to support type inquiry through isa, cast, and dyn_cast.
  62. static bool classof(const Value *V) {
  63. return V->getValueID() >= ConstantDataFirstVal &&
  64. V->getValueID() <= ConstantDataLastVal;
  65. }
  66. };
  67. //===----------------------------------------------------------------------===//
  68. /// This is the shared class of boolean and integer constants. This class
  69. /// represents both boolean and integral constants.
  70. /// Class for constant integers.
  71. class ConstantInt final : public ConstantData {
  72. friend class Constant;
  73. APInt Val;
  74. ConstantInt(IntegerType *Ty, const APInt &V);
  75. void destroyConstantImpl();
  76. public:
  77. ConstantInt(const ConstantInt &) = delete;
  78. static ConstantInt *getTrue(LLVMContext &Context);
  79. static ConstantInt *getFalse(LLVMContext &Context);
  80. static ConstantInt *getBool(LLVMContext &Context, bool V);
  81. static Constant *getTrue(Type *Ty);
  82. static Constant *getFalse(Type *Ty);
  83. static Constant *getBool(Type *Ty, bool V);
  84. /// If Ty is a vector type, return a Constant with a splat of the given
  85. /// value. Otherwise return a ConstantInt for the given value.
  86. static Constant *get(Type *Ty, uint64_t V, bool IsSigned = false);
  87. /// Return a ConstantInt with the specified integer value for the specified
  88. /// type. If the type is wider than 64 bits, the value will be zero-extended
  89. /// to fit the type, unless IsSigned is true, in which case the value will
  90. /// be interpreted as a 64-bit signed integer and sign-extended to fit
  91. /// the type.
  92. /// Get a ConstantInt for a specific value.
  93. static ConstantInt *get(IntegerType *Ty, uint64_t V, bool IsSigned = false);
  94. /// Return a ConstantInt with the specified value for the specified type. The
  95. /// value V will be canonicalized to a an unsigned APInt. Accessing it with
  96. /// either getSExtValue() or getZExtValue() will yield a correctly sized and
  97. /// signed value for the type Ty.
  98. /// Get a ConstantInt for a specific signed value.
  99. static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
  100. static Constant *getSigned(Type *Ty, int64_t V);
  101. /// Return a ConstantInt with the specified value and an implied Type. The
  102. /// type is the integer type that corresponds to the bit width of the value.
  103. static ConstantInt *get(LLVMContext &Context, const APInt &V);
  104. /// Return a ConstantInt constructed from the string strStart with the given
  105. /// radix.
  106. static ConstantInt *get(IntegerType *Ty, StringRef Str, uint8_t Radix);
  107. /// If Ty is a vector type, return a Constant with a splat of the given
  108. /// value. Otherwise return a ConstantInt for the given value.
  109. static Constant *get(Type *Ty, const APInt &V);
  110. /// Return the constant as an APInt value reference. This allows clients to
  111. /// obtain a full-precision copy of the value.
  112. /// Return the constant's value.
  113. inline const APInt &getValue() const { return Val; }
  114. /// getBitWidth - Return the bitwidth of this constant.
  115. unsigned getBitWidth() const { return Val.getBitWidth(); }
  116. /// Return the constant as a 64-bit unsigned integer value after it
  117. /// has been zero extended as appropriate for the type of this constant. Note
  118. /// that this method can assert if the value does not fit in 64 bits.
  119. /// Return the zero extended value.
  120. inline uint64_t getZExtValue() const { return Val.getZExtValue(); }
  121. /// Return the constant as a 64-bit integer value after it has been sign
  122. /// extended as appropriate for the type of this constant. Note that
  123. /// this method can assert if the value does not fit in 64 bits.
  124. /// Return the sign extended value.
  125. inline int64_t getSExtValue() const { return Val.getSExtValue(); }
  126. /// Return the constant as an llvm::MaybeAlign.
  127. /// Note that this method can assert if the value does not fit in 64 bits or
  128. /// is not a power of two.
  129. inline MaybeAlign getMaybeAlignValue() const {
  130. return MaybeAlign(getZExtValue());
  131. }
  132. /// Return the constant as an llvm::Align, interpreting `0` as `Align(1)`.
  133. /// Note that this method can assert if the value does not fit in 64 bits or
  134. /// is not a power of two.
  135. inline Align getAlignValue() const {
  136. return getMaybeAlignValue().valueOrOne();
  137. }
  138. /// A helper method that can be used to determine if the constant contained
  139. /// within is equal to a constant. This only works for very small values,
  140. /// because this is all that can be represented with all types.
  141. /// Determine if this constant's value is same as an unsigned char.
  142. bool equalsInt(uint64_t V) const { return Val == V; }
  143. /// getType - Specialize the getType() method to always return an IntegerType,
  144. /// which reduces the amount of casting needed in parts of the compiler.
  145. ///
  146. inline IntegerType *getType() const {
  147. return cast<IntegerType>(Value::getType());
  148. }
  149. /// This static method returns true if the type Ty is big enough to
  150. /// represent the value V. This can be used to avoid having the get method
  151. /// assert when V is larger than Ty can represent. Note that there are two
  152. /// versions of this method, one for unsigned and one for signed integers.
  153. /// Although ConstantInt canonicalizes everything to an unsigned integer,
  154. /// the signed version avoids callers having to convert a signed quantity
  155. /// to the appropriate unsigned type before calling the method.
  156. /// @returns true if V is a valid value for type Ty
  157. /// Determine if the value is in range for the given type.
  158. static bool isValueValidForType(Type *Ty, uint64_t V);
  159. static bool isValueValidForType(Type *Ty, int64_t V);
  160. bool isNegative() const { return Val.isNegative(); }
  161. /// This is just a convenience method to make client code smaller for a
  162. /// common code. It also correctly performs the comparison without the
  163. /// potential for an assertion from getZExtValue().
  164. bool isZero() const { return Val.isZero(); }
  165. /// This is just a convenience method to make client code smaller for a
  166. /// common case. It also correctly performs the comparison without the
  167. /// potential for an assertion from getZExtValue().
  168. /// Determine if the value is one.
  169. bool isOne() const { return Val.isOne(); }
  170. /// This function will return true iff every bit in this constant is set
  171. /// to true.
  172. /// @returns true iff this constant's bits are all set to true.
  173. /// Determine if the value is all ones.
  174. bool isMinusOne() const { return Val.isAllOnes(); }
  175. /// This function will return true iff this constant represents the largest
  176. /// value that may be represented by the constant's type.
  177. /// @returns true iff this is the largest value that may be represented
  178. /// by this type.
  179. /// Determine if the value is maximal.
  180. bool isMaxValue(bool IsSigned) const {
  181. if (IsSigned)
  182. return Val.isMaxSignedValue();
  183. else
  184. return Val.isMaxValue();
  185. }
  186. /// This function will return true iff this constant represents the smallest
  187. /// value that may be represented by this constant's type.
  188. /// @returns true if this is the smallest value that may be represented by
  189. /// this type.
  190. /// Determine if the value is minimal.
  191. bool isMinValue(bool IsSigned) const {
  192. if (IsSigned)
  193. return Val.isMinSignedValue();
  194. else
  195. return Val.isMinValue();
  196. }
  197. /// This function will return true iff this constant represents a value with
  198. /// active bits bigger than 64 bits or a value greater than the given uint64_t
  199. /// value.
  200. /// @returns true iff this constant is greater or equal to the given number.
  201. /// Determine if the value is greater or equal to the given number.
  202. bool uge(uint64_t Num) const { return Val.uge(Num); }
  203. /// getLimitedValue - If the value is smaller than the specified limit,
  204. /// return it, otherwise return the limit value. This causes the value
  205. /// to saturate to the limit.
  206. /// @returns the min of the value of the constant and the specified value
  207. /// Get the constant's value with a saturation limit
  208. uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
  209. return Val.getLimitedValue(Limit);
  210. }
  211. /// Methods to support type inquiry through isa, cast, and dyn_cast.
  212. static bool classof(const Value *V) {
  213. return V->getValueID() == ConstantIntVal;
  214. }
  215. };
  216. //===----------------------------------------------------------------------===//
  217. /// ConstantFP - Floating Point Values [float, double]
  218. ///
  219. class ConstantFP final : public ConstantData {
  220. friend class Constant;
  221. APFloat Val;
  222. ConstantFP(Type *Ty, const APFloat &V);
  223. void destroyConstantImpl();
  224. public:
  225. ConstantFP(const ConstantFP &) = delete;
  226. /// Floating point negation must be implemented with f(x) = -0.0 - x. This
  227. /// method returns the negative zero constant for floating point or vector
  228. /// floating point types; for all other types, it returns the null value.
  229. static Constant *getZeroValueForNegation(Type *Ty);
  230. /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP,
  231. /// for the specified value in the specified type. This should only be used
  232. /// for simple constant values like 2.0/1.0 etc, that are known-valid both as
  233. /// host double and as the target format.
  234. static Constant *get(Type *Ty, double V);
  235. /// If Ty is a vector type, return a Constant with a splat of the given
  236. /// value. Otherwise return a ConstantFP for the given value.
  237. static Constant *get(Type *Ty, const APFloat &V);
  238. static Constant *get(Type *Ty, StringRef Str);
  239. static ConstantFP *get(LLVMContext &Context, const APFloat &V);
  240. static Constant *getNaN(Type *Ty, bool Negative = false,
  241. uint64_t Payload = 0);
  242. static Constant *getQNaN(Type *Ty, bool Negative = false,
  243. APInt *Payload = nullptr);
  244. static Constant *getSNaN(Type *Ty, bool Negative = false,
  245. APInt *Payload = nullptr);
  246. static Constant *getZero(Type *Ty, bool Negative = false);
  247. static Constant *getNegativeZero(Type *Ty) { return getZero(Ty, true); }
  248. static Constant *getInfinity(Type *Ty, bool Negative = false);
  249. /// Return true if Ty is big enough to represent V.
  250. static bool isValueValidForType(Type *Ty, const APFloat &V);
  251. inline const APFloat &getValueAPF() const { return Val; }
  252. inline const APFloat &getValue() const { return Val; }
  253. /// Return true if the value is positive or negative zero.
  254. bool isZero() const { return Val.isZero(); }
  255. /// Return true if the sign bit is set.
  256. bool isNegative() const { return Val.isNegative(); }
  257. /// Return true if the value is infinity
  258. bool isInfinity() const { return Val.isInfinity(); }
  259. /// Return true if the value is a NaN.
  260. bool isNaN() const { return Val.isNaN(); }
  261. /// We don't rely on operator== working on double values, as it returns true
  262. /// for things that are clearly not equal, like -0.0 and 0.0.
  263. /// As such, this method can be used to do an exact bit-for-bit comparison of
  264. /// two floating point values. The version with a double operand is retained
  265. /// because it's so convenient to write isExactlyValue(2.0), but please use
  266. /// it only for simple constants.
  267. bool isExactlyValue(const APFloat &V) const;
  268. bool isExactlyValue(double V) const {
  269. bool ignored;
  270. APFloat FV(V);
  271. FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
  272. return isExactlyValue(FV);
  273. }
  274. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  275. static bool classof(const Value *V) {
  276. return V->getValueID() == ConstantFPVal;
  277. }
  278. };
  279. //===----------------------------------------------------------------------===//
  280. /// All zero aggregate value
  281. ///
  282. class ConstantAggregateZero final : public ConstantData {
  283. friend class Constant;
  284. explicit ConstantAggregateZero(Type *Ty)
  285. : ConstantData(Ty, ConstantAggregateZeroVal) {}
  286. void destroyConstantImpl();
  287. public:
  288. ConstantAggregateZero(const ConstantAggregateZero &) = delete;
  289. static ConstantAggregateZero *get(Type *Ty);
  290. /// If this CAZ has array or vector type, return a zero with the right element
  291. /// type.
  292. Constant *getSequentialElement() const;
  293. /// If this CAZ has struct type, return a zero with the right element type for
  294. /// the specified element.
  295. Constant *getStructElement(unsigned Elt) const;
  296. /// Return a zero of the right value for the specified GEP index if we can,
  297. /// otherwise return null (e.g. if C is a ConstantExpr).
  298. Constant *getElementValue(Constant *C) const;
  299. /// Return a zero of the right value for the specified GEP index.
  300. Constant *getElementValue(unsigned Idx) const;
  301. /// Return the number of elements in the array, vector, or struct.
  302. ElementCount getElementCount() const;
  303. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  304. ///
  305. static bool classof(const Value *V) {
  306. return V->getValueID() == ConstantAggregateZeroVal;
  307. }
  308. };
  309. /// Base class for aggregate constants (with operands).
  310. ///
  311. /// These constants are aggregates of other constants, which are stored as
  312. /// operands.
  313. ///
  314. /// Subclasses are \a ConstantStruct, \a ConstantArray, and \a
  315. /// ConstantVector.
  316. ///
  317. /// \note Some subclasses of \a ConstantData are semantically aggregates --
  318. /// such as \a ConstantDataArray -- but are not subclasses of this because they
  319. /// use operands.
  320. class ConstantAggregate : public Constant {
  321. protected:
  322. ConstantAggregate(Type *T, ValueTy VT, ArrayRef<Constant *> V);
  323. public:
  324. /// Transparently provide more efficient getOperand methods.
  325. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
  326. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  327. static bool classof(const Value *V) {
  328. return V->getValueID() >= ConstantAggregateFirstVal &&
  329. V->getValueID() <= ConstantAggregateLastVal;
  330. }
  331. };
  332. template <>
  333. struct OperandTraits<ConstantAggregate>
  334. : public VariadicOperandTraits<ConstantAggregate> {};
  335. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant)
  336. //===----------------------------------------------------------------------===//
  337. /// ConstantArray - Constant Array Declarations
  338. ///
  339. class ConstantArray final : public ConstantAggregate {
  340. friend struct ConstantAggrKeyType<ConstantArray>;
  341. friend class Constant;
  342. ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
  343. void destroyConstantImpl();
  344. Value *handleOperandChangeImpl(Value *From, Value *To);
  345. public:
  346. // ConstantArray accessors
  347. static Constant *get(ArrayType *T, ArrayRef<Constant *> V);
  348. private:
  349. static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V);
  350. public:
  351. /// Specialize the getType() method to always return an ArrayType,
  352. /// which reduces the amount of casting needed in parts of the compiler.
  353. inline ArrayType *getType() const {
  354. return cast<ArrayType>(Value::getType());
  355. }
  356. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  357. static bool classof(const Value *V) {
  358. return V->getValueID() == ConstantArrayVal;
  359. }
  360. };
  361. //===----------------------------------------------------------------------===//
  362. // Constant Struct Declarations
  363. //
  364. class ConstantStruct final : public ConstantAggregate {
  365. friend struct ConstantAggrKeyType<ConstantStruct>;
  366. friend class Constant;
  367. ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
  368. void destroyConstantImpl();
  369. Value *handleOperandChangeImpl(Value *From, Value *To);
  370. public:
  371. // ConstantStruct accessors
  372. static Constant *get(StructType *T, ArrayRef<Constant *> V);
  373. template <typename... Csts>
  374. static std::enable_if_t<are_base_of<Constant, Csts...>::value, Constant *>
  375. get(StructType *T, Csts *...Vs) {
  376. return get(T, ArrayRef<Constant *>({Vs...}));
  377. }
  378. /// Return an anonymous struct that has the specified elements.
  379. /// If the struct is possibly empty, then you must specify a context.
  380. static Constant *getAnon(ArrayRef<Constant *> V, bool Packed = false) {
  381. return get(getTypeForElements(V, Packed), V);
  382. }
  383. static Constant *getAnon(LLVMContext &Ctx, ArrayRef<Constant *> V,
  384. bool Packed = false) {
  385. return get(getTypeForElements(Ctx, V, Packed), V);
  386. }
  387. /// Return an anonymous struct type to use for a constant with the specified
  388. /// set of elements. The list must not be empty.
  389. static StructType *getTypeForElements(ArrayRef<Constant *> V,
  390. bool Packed = false);
  391. /// This version of the method allows an empty list.
  392. static StructType *getTypeForElements(LLVMContext &Ctx,
  393. ArrayRef<Constant *> V,
  394. bool Packed = false);
  395. /// Specialization - reduce amount of casting.
  396. inline StructType *getType() const {
  397. return cast<StructType>(Value::getType());
  398. }
  399. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  400. static bool classof(const Value *V) {
  401. return V->getValueID() == ConstantStructVal;
  402. }
  403. };
  404. //===----------------------------------------------------------------------===//
  405. /// Constant Vector Declarations
  406. ///
  407. class ConstantVector final : public ConstantAggregate {
  408. friend struct ConstantAggrKeyType<ConstantVector>;
  409. friend class Constant;
  410. ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
  411. void destroyConstantImpl();
  412. Value *handleOperandChangeImpl(Value *From, Value *To);
  413. public:
  414. // ConstantVector accessors
  415. static Constant *get(ArrayRef<Constant *> V);
  416. private:
  417. static Constant *getImpl(ArrayRef<Constant *> V);
  418. public:
  419. /// Return a ConstantVector with the specified constant in each element.
  420. /// Note that this might not return an instance of ConstantVector
  421. static Constant *getSplat(ElementCount EC, Constant *Elt);
  422. /// Specialize the getType() method to always return a FixedVectorType,
  423. /// which reduces the amount of casting needed in parts of the compiler.
  424. inline FixedVectorType *getType() const {
  425. return cast<FixedVectorType>(Value::getType());
  426. }
  427. /// If all elements of the vector constant have the same value, return that
  428. /// value. Otherwise, return nullptr. Ignore undefined elements by setting
  429. /// AllowUndefs to true.
  430. Constant *getSplatValue(bool AllowUndefs = false) const;
  431. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  432. static bool classof(const Value *V) {
  433. return V->getValueID() == ConstantVectorVal;
  434. }
  435. };
  436. //===----------------------------------------------------------------------===//
  437. /// A constant pointer value that points to null
  438. ///
  439. class ConstantPointerNull final : public ConstantData {
  440. friend class Constant;
  441. explicit ConstantPointerNull(PointerType *T)
  442. : ConstantData(T, Value::ConstantPointerNullVal) {}
  443. void destroyConstantImpl();
  444. public:
  445. ConstantPointerNull(const ConstantPointerNull &) = delete;
  446. /// Static factory methods - Return objects of the specified value
  447. static ConstantPointerNull *get(PointerType *T);
  448. /// Specialize the getType() method to always return an PointerType,
  449. /// which reduces the amount of casting needed in parts of the compiler.
  450. inline PointerType *getType() const {
  451. return cast<PointerType>(Value::getType());
  452. }
  453. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  454. static bool classof(const Value *V) {
  455. return V->getValueID() == ConstantPointerNullVal;
  456. }
  457. };
  458. //===----------------------------------------------------------------------===//
  459. /// ConstantDataSequential - A vector or array constant whose element type is a
  460. /// simple 1/2/4/8-byte integer or half/bfloat/float/double, and whose elements
  461. /// are just simple data values (i.e. ConstantInt/ConstantFP). This Constant
  462. /// node has no operands because it stores all of the elements of the constant
  463. /// as densely packed data, instead of as Value*'s.
  464. ///
  465. /// This is the common base class of ConstantDataArray and ConstantDataVector.
  466. ///
  467. class ConstantDataSequential : public ConstantData {
  468. friend class LLVMContextImpl;
  469. friend class Constant;
  470. /// A pointer to the bytes underlying this constant (which is owned by the
  471. /// uniquing StringMap).
  472. const char *DataElements;
  473. /// This forms a link list of ConstantDataSequential nodes that have
  474. /// the same value but different type. For example, 0,0,0,1 could be a 4
  475. /// element array of i8, or a 1-element array of i32. They'll both end up in
  476. /// the same StringMap bucket, linked up.
  477. std::unique_ptr<ConstantDataSequential> Next;
  478. void destroyConstantImpl();
  479. protected:
  480. explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
  481. : ConstantData(ty, VT), DataElements(Data) {}
  482. static Constant *getImpl(StringRef Bytes, Type *Ty);
  483. public:
  484. ConstantDataSequential(const ConstantDataSequential &) = delete;
  485. /// Return true if a ConstantDataSequential can be formed with a vector or
  486. /// array of the specified element type.
  487. /// ConstantDataArray only works with normal float and int types that are
  488. /// stored densely in memory, not with things like i42 or x86_f80.
  489. static bool isElementTypeCompatible(Type *Ty);
  490. /// If this is a sequential container of integers (of any size), return the
  491. /// specified element in the low bits of a uint64_t.
  492. uint64_t getElementAsInteger(unsigned i) const;
  493. /// If this is a sequential container of integers (of any size), return the
  494. /// specified element as an APInt.
  495. APInt getElementAsAPInt(unsigned i) const;
  496. /// If this is a sequential container of floating point type, return the
  497. /// specified element as an APFloat.
  498. APFloat getElementAsAPFloat(unsigned i) const;
  499. /// If this is an sequential container of floats, return the specified element
  500. /// as a float.
  501. float getElementAsFloat(unsigned i) const;
  502. /// If this is an sequential container of doubles, return the specified
  503. /// element as a double.
  504. double getElementAsDouble(unsigned i) const;
  505. /// Return a Constant for a specified index's element.
  506. /// Note that this has to compute a new constant to return, so it isn't as
  507. /// efficient as getElementAsInteger/Float/Double.
  508. Constant *getElementAsConstant(unsigned i) const;
  509. /// Return the element type of the array/vector.
  510. Type *getElementType() const;
  511. /// Return the number of elements in the array or vector.
  512. unsigned getNumElements() const;
  513. /// Return the size (in bytes) of each element in the array/vector.
  514. /// The size of the elements is known to be a multiple of one byte.
  515. uint64_t getElementByteSize() const;
  516. /// This method returns true if this is an array of \p CharSize integers.
  517. bool isString(unsigned CharSize = 8) const;
  518. /// This method returns true if the array "isString", ends with a null byte,
  519. /// and does not contains any other null bytes.
  520. bool isCString() const;
  521. /// If this array is isString(), then this method returns the array as a
  522. /// StringRef. Otherwise, it asserts out.
  523. StringRef getAsString() const {
  524. assert(isString() && "Not a string");
  525. return getRawDataValues();
  526. }
  527. /// If this array is isCString(), then this method returns the array (without
  528. /// the trailing null byte) as a StringRef. Otherwise, it asserts out.
  529. StringRef getAsCString() const {
  530. assert(isCString() && "Isn't a C string");
  531. StringRef Str = getAsString();
  532. return Str.substr(0, Str.size() - 1);
  533. }
  534. /// Return the raw, underlying, bytes of this data. Note that this is an
  535. /// extremely tricky thing to work with, as it exposes the host endianness of
  536. /// the data elements.
  537. StringRef getRawDataValues() const;
  538. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  539. static bool classof(const Value *V) {
  540. return V->getValueID() == ConstantDataArrayVal ||
  541. V->getValueID() == ConstantDataVectorVal;
  542. }
  543. private:
  544. const char *getElementPointer(unsigned Elt) const;
  545. };
  546. //===----------------------------------------------------------------------===//
  547. /// An array constant whose element type is a simple 1/2/4/8-byte integer or
  548. /// float/double, and whose elements are just simple data values
  549. /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
  550. /// stores all of the elements of the constant as densely packed data, instead
  551. /// of as Value*'s.
  552. class ConstantDataArray final : public ConstantDataSequential {
  553. friend class ConstantDataSequential;
  554. explicit ConstantDataArray(Type *ty, const char *Data)
  555. : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
  556. public:
  557. ConstantDataArray(const ConstantDataArray &) = delete;
  558. /// get() constructor - Return a constant with array type with an element
  559. /// count and element type matching the ArrayRef passed in. Note that this
  560. /// can return a ConstantAggregateZero object.
  561. template <typename ElementTy>
  562. static Constant *get(LLVMContext &Context, ArrayRef<ElementTy> Elts) {
  563. const char *Data = reinterpret_cast<const char *>(Elts.data());
  564. return getRaw(StringRef(Data, Elts.size() * sizeof(ElementTy)), Elts.size(),
  565. Type::getScalarTy<ElementTy>(Context));
  566. }
  567. /// get() constructor - ArrayTy needs to be compatible with
  568. /// ArrayRef<ElementTy>. Calls get(LLVMContext, ArrayRef<ElementTy>).
  569. template <typename ArrayTy>
  570. static Constant *get(LLVMContext &Context, ArrayTy &Elts) {
  571. return ConstantDataArray::get(Context, ArrayRef(Elts));
  572. }
  573. /// getRaw() constructor - Return a constant with array type with an element
  574. /// count and element type matching the NumElements and ElementTy parameters
  575. /// passed in. Note that this can return a ConstantAggregateZero object.
  576. /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
  577. /// the buffer containing the elements. Be careful to make sure Data uses the
  578. /// right endianness, the buffer will be used as-is.
  579. static Constant *getRaw(StringRef Data, uint64_t NumElements,
  580. Type *ElementTy) {
  581. Type *Ty = ArrayType::get(ElementTy, NumElements);
  582. return getImpl(Data, Ty);
  583. }
  584. /// getFP() constructors - Return a constant of array type with a float
  585. /// element type taken from argument `ElementType', and count taken from
  586. /// argument `Elts'. The amount of bits of the contained type must match the
  587. /// number of bits of the type contained in the passed in ArrayRef.
  588. /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
  589. /// that this can return a ConstantAggregateZero object.
  590. static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
  591. static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
  592. static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
  593. /// This method constructs a CDS and initializes it with a text string.
  594. /// The default behavior (AddNull==true) causes a null terminator to
  595. /// be placed at the end of the array (increasing the length of the string by
  596. /// one more than the StringRef would normally indicate. Pass AddNull=false
  597. /// to disable this behavior.
  598. static Constant *getString(LLVMContext &Context, StringRef Initializer,
  599. bool AddNull = true);
  600. /// Specialize the getType() method to always return an ArrayType,
  601. /// which reduces the amount of casting needed in parts of the compiler.
  602. inline ArrayType *getType() const {
  603. return cast<ArrayType>(Value::getType());
  604. }
  605. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  606. static bool classof(const Value *V) {
  607. return V->getValueID() == ConstantDataArrayVal;
  608. }
  609. };
  610. //===----------------------------------------------------------------------===//
  611. /// A vector constant whose element type is a simple 1/2/4/8-byte integer or
  612. /// float/double, and whose elements are just simple data values
  613. /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
  614. /// stores all of the elements of the constant as densely packed data, instead
  615. /// of as Value*'s.
  616. class ConstantDataVector final : public ConstantDataSequential {
  617. friend class ConstantDataSequential;
  618. explicit ConstantDataVector(Type *ty, const char *Data)
  619. : ConstantDataSequential(ty, ConstantDataVectorVal, Data),
  620. IsSplatSet(false) {}
  621. // Cache whether or not the constant is a splat.
  622. mutable bool IsSplatSet : 1;
  623. mutable bool IsSplat : 1;
  624. bool isSplatData() const;
  625. public:
  626. ConstantDataVector(const ConstantDataVector &) = delete;
  627. /// get() constructors - Return a constant with vector type with an element
  628. /// count and element type matching the ArrayRef passed in. Note that this
  629. /// can return a ConstantAggregateZero object.
  630. static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
  631. static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
  632. static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
  633. static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
  634. static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
  635. static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
  636. /// getRaw() constructor - Return a constant with vector type with an element
  637. /// count and element type matching the NumElements and ElementTy parameters
  638. /// passed in. Note that this can return a ConstantAggregateZero object.
  639. /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
  640. /// the buffer containing the elements. Be careful to make sure Data uses the
  641. /// right endianness, the buffer will be used as-is.
  642. static Constant *getRaw(StringRef Data, uint64_t NumElements,
  643. Type *ElementTy) {
  644. Type *Ty = VectorType::get(ElementTy, ElementCount::getFixed(NumElements));
  645. return getImpl(Data, Ty);
  646. }
  647. /// getFP() constructors - Return a constant of vector type with a float
  648. /// element type taken from argument `ElementType', and count taken from
  649. /// argument `Elts'. The amount of bits of the contained type must match the
  650. /// number of bits of the type contained in the passed in ArrayRef.
  651. /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
  652. /// that this can return a ConstantAggregateZero object.
  653. static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
  654. static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
  655. static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
  656. /// Return a ConstantVector with the specified constant in each element.
  657. /// The specified constant has to be a of a compatible type (i8/i16/
  658. /// i32/i64/half/bfloat/float/double) and must be a ConstantFP or ConstantInt.
  659. static Constant *getSplat(unsigned NumElts, Constant *Elt);
  660. /// Returns true if this is a splat constant, meaning that all elements have
  661. /// the same value.
  662. bool isSplat() const;
  663. /// If this is a splat constant, meaning that all of the elements have the
  664. /// same value, return that value. Otherwise return NULL.
  665. Constant *getSplatValue() const;
  666. /// Specialize the getType() method to always return a FixedVectorType,
  667. /// which reduces the amount of casting needed in parts of the compiler.
  668. inline FixedVectorType *getType() const {
  669. return cast<FixedVectorType>(Value::getType());
  670. }
  671. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  672. static bool classof(const Value *V) {
  673. return V->getValueID() == ConstantDataVectorVal;
  674. }
  675. };
  676. //===----------------------------------------------------------------------===//
  677. /// A constant token which is empty
  678. ///
  679. class ConstantTokenNone final : public ConstantData {
  680. friend class Constant;
  681. explicit ConstantTokenNone(LLVMContext &Context)
  682. : ConstantData(Type::getTokenTy(Context), ConstantTokenNoneVal) {}
  683. void destroyConstantImpl();
  684. public:
  685. ConstantTokenNone(const ConstantTokenNone &) = delete;
  686. /// Return the ConstantTokenNone.
  687. static ConstantTokenNone *get(LLVMContext &Context);
  688. /// Methods to support type inquiry through isa, cast, and dyn_cast.
  689. static bool classof(const Value *V) {
  690. return V->getValueID() == ConstantTokenNoneVal;
  691. }
  692. };
  693. /// A constant target extension type default initializer
  694. class ConstantTargetNone final : public ConstantData {
  695. friend class Constant;
  696. explicit ConstantTargetNone(TargetExtType *T)
  697. : ConstantData(T, Value::ConstantTargetNoneVal) {}
  698. void destroyConstantImpl();
  699. public:
  700. ConstantTargetNone(const ConstantTargetNone &) = delete;
  701. /// Static factory methods - Return objects of the specified value.
  702. static ConstantTargetNone *get(TargetExtType *T);
  703. /// Specialize the getType() method to always return an TargetExtType,
  704. /// which reduces the amount of casting needed in parts of the compiler.
  705. inline TargetExtType *getType() const {
  706. return cast<TargetExtType>(Value::getType());
  707. }
  708. /// Methods for support type inquiry through isa, cast, and dyn_cast.
  709. static bool classof(const Value *V) {
  710. return V->getValueID() == ConstantTargetNoneVal;
  711. }
  712. };
  713. /// The address of a basic block.
  714. ///
  715. class BlockAddress final : public Constant {
  716. friend class Constant;
  717. BlockAddress(Function *F, BasicBlock *BB);
  718. void *operator new(size_t S) { return User::operator new(S, 2); }
  719. void destroyConstantImpl();
  720. Value *handleOperandChangeImpl(Value *From, Value *To);
  721. public:
  722. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  723. /// Return a BlockAddress for the specified function and basic block.
  724. static BlockAddress *get(Function *F, BasicBlock *BB);
  725. /// Return a BlockAddress for the specified basic block. The basic
  726. /// block must be embedded into a function.
  727. static BlockAddress *get(BasicBlock *BB);
  728. /// Lookup an existing \c BlockAddress constant for the given BasicBlock.
  729. ///
  730. /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
  731. static BlockAddress *lookup(const BasicBlock *BB);
  732. /// Transparently provide more efficient getOperand methods.
  733. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  734. Function *getFunction() const { return (Function *)Op<0>().get(); }
  735. BasicBlock *getBasicBlock() const { return (BasicBlock *)Op<1>().get(); }
  736. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  737. static bool classof(const Value *V) {
  738. return V->getValueID() == BlockAddressVal;
  739. }
  740. };
  741. template <>
  742. struct OperandTraits<BlockAddress>
  743. : public FixedNumOperandTraits<BlockAddress, 2> {};
  744. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
  745. /// Wrapper for a function that represents a value that
  746. /// functionally represents the original function. This can be a function,
  747. /// global alias to a function, or an ifunc.
  748. class DSOLocalEquivalent final : public Constant {
  749. friend class Constant;
  750. DSOLocalEquivalent(GlobalValue *GV);
  751. void *operator new(size_t S) { return User::operator new(S, 1); }
  752. void destroyConstantImpl();
  753. Value *handleOperandChangeImpl(Value *From, Value *To);
  754. public:
  755. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  756. /// Return a DSOLocalEquivalent for the specified global value.
  757. static DSOLocalEquivalent *get(GlobalValue *GV);
  758. /// Transparently provide more efficient getOperand methods.
  759. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  760. GlobalValue *getGlobalValue() const {
  761. return cast<GlobalValue>(Op<0>().get());
  762. }
  763. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  764. static bool classof(const Value *V) {
  765. return V->getValueID() == DSOLocalEquivalentVal;
  766. }
  767. };
  768. template <>
  769. struct OperandTraits<DSOLocalEquivalent>
  770. : public FixedNumOperandTraits<DSOLocalEquivalent, 1> {};
  771. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(DSOLocalEquivalent, Value)
  772. /// Wrapper for a value that won't be replaced with a CFI jump table
  773. /// pointer in LowerTypeTestsModule.
  774. class NoCFIValue final : public Constant {
  775. friend class Constant;
  776. NoCFIValue(GlobalValue *GV);
  777. void *operator new(size_t S) { return User::operator new(S, 1); }
  778. void destroyConstantImpl();
  779. Value *handleOperandChangeImpl(Value *From, Value *To);
  780. public:
  781. /// Return a NoCFIValue for the specified function.
  782. static NoCFIValue *get(GlobalValue *GV);
  783. /// Transparently provide more efficient getOperand methods.
  784. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  785. GlobalValue *getGlobalValue() const {
  786. return cast<GlobalValue>(Op<0>().get());
  787. }
  788. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  789. static bool classof(const Value *V) {
  790. return V->getValueID() == NoCFIValueVal;
  791. }
  792. };
  793. template <>
  794. struct OperandTraits<NoCFIValue> : public FixedNumOperandTraits<NoCFIValue, 1> {
  795. };
  796. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(NoCFIValue, Value)
  797. //===----------------------------------------------------------------------===//
  798. /// A constant value that is initialized with an expression using
  799. /// other constant values.
  800. ///
  801. /// This class uses the standard Instruction opcodes to define the various
  802. /// constant expressions. The Opcode field for the ConstantExpr class is
  803. /// maintained in the Value::SubclassData field.
  804. class ConstantExpr : public Constant {
  805. friend struct ConstantExprKeyType;
  806. friend class Constant;
  807. void destroyConstantImpl();
  808. Value *handleOperandChangeImpl(Value *From, Value *To);
  809. protected:
  810. ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
  811. : Constant(ty, ConstantExprVal, Ops, NumOps) {
  812. // Operation type (an Instruction opcode) is stored as the SubclassData.
  813. setValueSubclassData(Opcode);
  814. }
  815. ~ConstantExpr() = default;
  816. public:
  817. // Static methods to construct a ConstantExpr of different kinds. Note that
  818. // these methods may return a object that is not an instance of the
  819. // ConstantExpr class, because they will attempt to fold the constant
  820. // expression into something simpler if possible.
  821. /// getAlignOf constant expr - computes the alignment of a type in a target
  822. /// independent way (Note: the return type is an i64).
  823. static Constant *getAlignOf(Type *Ty);
  824. /// getSizeOf constant expr - computes the (alloc) size of a type (in
  825. /// address-units, not bits) in a target independent way (Note: the return
  826. /// type is an i64).
  827. ///
  828. static Constant *getSizeOf(Type *Ty);
  829. /// getOffsetOf constant expr - computes the offset of a struct field in a
  830. /// target independent way (Note: the return type is an i64).
  831. ///
  832. static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
  833. /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
  834. /// which supports any aggregate type, and any Constant index.
  835. ///
  836. static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
  837. static Constant *getNeg(Constant *C, bool HasNUW = false,
  838. bool HasNSW = false);
  839. static Constant *getNot(Constant *C);
  840. static Constant *getAdd(Constant *C1, Constant *C2, bool HasNUW = false,
  841. bool HasNSW = false);
  842. static Constant *getSub(Constant *C1, Constant *C2, bool HasNUW = false,
  843. bool HasNSW = false);
  844. static Constant *getMul(Constant *C1, Constant *C2, bool HasNUW = false,
  845. bool HasNSW = false);
  846. static Constant *getAnd(Constant *C1, Constant *C2);
  847. static Constant *getOr(Constant *C1, Constant *C2);
  848. static Constant *getXor(Constant *C1, Constant *C2);
  849. static Constant *getUMin(Constant *C1, Constant *C2);
  850. static Constant *getShl(Constant *C1, Constant *C2, bool HasNUW = false,
  851. bool HasNSW = false);
  852. static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
  853. static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
  854. static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  855. static Constant *getSExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  856. static Constant *getZExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  857. static Constant *getFPTrunc(Constant *C, Type *Ty,
  858. bool OnlyIfReduced = false);
  859. static Constant *getFPExtend(Constant *C, Type *Ty,
  860. bool OnlyIfReduced = false);
  861. static Constant *getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  862. static Constant *getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  863. static Constant *getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  864. static Constant *getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  865. static Constant *getPtrToInt(Constant *C, Type *Ty,
  866. bool OnlyIfReduced = false);
  867. static Constant *getIntToPtr(Constant *C, Type *Ty,
  868. bool OnlyIfReduced = false);
  869. static Constant *getBitCast(Constant *C, Type *Ty,
  870. bool OnlyIfReduced = false);
  871. static Constant *getAddrSpaceCast(Constant *C, Type *Ty,
  872. bool OnlyIfReduced = false);
  873. static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
  874. static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
  875. static Constant *getNSWAdd(Constant *C1, Constant *C2) {
  876. return getAdd(C1, C2, false, true);
  877. }
  878. static Constant *getNUWAdd(Constant *C1, Constant *C2) {
  879. return getAdd(C1, C2, true, false);
  880. }
  881. static Constant *getNSWSub(Constant *C1, Constant *C2) {
  882. return getSub(C1, C2, false, true);
  883. }
  884. static Constant *getNUWSub(Constant *C1, Constant *C2) {
  885. return getSub(C1, C2, true, false);
  886. }
  887. static Constant *getNSWMul(Constant *C1, Constant *C2) {
  888. return getMul(C1, C2, false, true);
  889. }
  890. static Constant *getNUWMul(Constant *C1, Constant *C2) {
  891. return getMul(C1, C2, true, false);
  892. }
  893. static Constant *getNSWShl(Constant *C1, Constant *C2) {
  894. return getShl(C1, C2, false, true);
  895. }
  896. static Constant *getNUWShl(Constant *C1, Constant *C2) {
  897. return getShl(C1, C2, true, false);
  898. }
  899. static Constant *getExactAShr(Constant *C1, Constant *C2) {
  900. return getAShr(C1, C2, true);
  901. }
  902. static Constant *getExactLShr(Constant *C1, Constant *C2) {
  903. return getLShr(C1, C2, true);
  904. }
  905. /// If C is a scalar/fixed width vector of known powers of 2, then this
  906. /// function returns a new scalar/fixed width vector obtained from logBase2
  907. /// of C. Undef vector elements are set to zero.
  908. /// Return a null pointer otherwise.
  909. static Constant *getExactLogBase2(Constant *C);
  910. /// Return the identity constant for a binary opcode.
  911. /// The identity constant C is defined as X op C = X and C op X = X for every
  912. /// X when the binary operation is commutative. If the binop is not
  913. /// commutative, callers can acquire the operand 1 identity constant by
  914. /// setting AllowRHSConstant to true. For example, any shift has a zero
  915. /// identity constant for operand 1: X shift 0 = X.
  916. /// If this is a fadd/fsub operation and we don't care about signed zeros,
  917. /// then setting NSZ to true returns the identity +0.0 instead of -0.0.
  918. /// Return nullptr if the operator does not have an identity constant.
  919. static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty,
  920. bool AllowRHSConstant = false,
  921. bool NSZ = false);
  922. /// Return the absorbing element for the given binary
  923. /// operation, i.e. a constant C such that X op C = C and C op X = C for
  924. /// every X. For example, this returns zero for integer multiplication.
  925. /// It returns null if the operator doesn't have an absorbing element.
  926. static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
  927. /// Transparently provide more efficient getOperand methods.
  928. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
  929. /// Convenience function for getting a Cast operation.
  930. ///
  931. /// \param ops The opcode for the conversion
  932. /// \param C The constant to be converted
  933. /// \param Ty The type to which the constant is converted
  934. /// \param OnlyIfReduced see \a getWithOperands() docs.
  935. static Constant *getCast(unsigned ops, Constant *C, Type *Ty,
  936. bool OnlyIfReduced = false);
  937. // Create a ZExt or BitCast cast constant expression
  938. static Constant *
  939. getZExtOrBitCast(Constant *C, ///< The constant to zext or bitcast
  940. Type *Ty ///< The type to zext or bitcast C to
  941. );
  942. // Create a SExt or BitCast cast constant expression
  943. static Constant *
  944. getSExtOrBitCast(Constant *C, ///< The constant to sext or bitcast
  945. Type *Ty ///< The type to sext or bitcast C to
  946. );
  947. // Create a Trunc or BitCast cast constant expression
  948. static Constant *
  949. getTruncOrBitCast(Constant *C, ///< The constant to trunc or bitcast
  950. Type *Ty ///< The type to trunc or bitcast C to
  951. );
  952. /// Create either an sext, trunc or nothing, depending on whether Ty is
  953. /// wider, narrower or the same as C->getType(). This only works with
  954. /// integer or vector of integer types.
  955. static Constant *getSExtOrTrunc(Constant *C, Type *Ty);
  956. /// Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
  957. /// expression.
  958. static Constant *
  959. getPointerCast(Constant *C, ///< The pointer value to be casted (operand 0)
  960. Type *Ty ///< The type to which cast should be made
  961. );
  962. /// Create a BitCast or AddrSpaceCast for a pointer type depending on
  963. /// the address space.
  964. static Constant *getPointerBitCastOrAddrSpaceCast(
  965. Constant *C, ///< The constant to addrspacecast or bitcast
  966. Type *Ty ///< The type to bitcast or addrspacecast C to
  967. );
  968. /// Create a ZExt, Bitcast or Trunc for integer -> integer casts
  969. static Constant *
  970. getIntegerCast(Constant *C, ///< The integer constant to be casted
  971. Type *Ty, ///< The integer type to cast to
  972. bool IsSigned ///< Whether C should be treated as signed or not
  973. );
  974. /// Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
  975. static Constant *getFPCast(Constant *C, ///< The integer constant to be casted
  976. Type *Ty ///< The integer type to cast to
  977. );
  978. /// Return true if this is a convert constant expression
  979. bool isCast() const;
  980. /// Return true if this is a compare constant expression
  981. bool isCompare() const;
  982. /// Select constant expr
  983. ///
  984. /// \param OnlyIfReducedTy see \a getWithOperands() docs.
  985. static Constant *getSelect(Constant *C, Constant *V1, Constant *V2,
  986. Type *OnlyIfReducedTy = nullptr);
  987. /// get - Return a binary or shift operator constant expression,
  988. /// folding if possible.
  989. ///
  990. /// \param OnlyIfReducedTy see \a getWithOperands() docs.
  991. static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
  992. unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr);
  993. /// Return an ICmp or FCmp comparison operator constant expression.
  994. ///
  995. /// \param OnlyIfReduced see \a getWithOperands() docs.
  996. static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2,
  997. bool OnlyIfReduced = false);
  998. /// get* - Return some common constants without having to
  999. /// specify the full Instruction::OPCODE identifier.
  1000. ///
  1001. static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS,
  1002. bool OnlyIfReduced = false);
  1003. static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS,
  1004. bool OnlyIfReduced = false);
  1005. /// Getelementptr form. Value* is only accepted for convenience;
  1006. /// all elements must be Constants.
  1007. ///
  1008. /// \param InRangeIndex the inrange index if present or std::nullopt.
  1009. /// \param OnlyIfReducedTy see \a getWithOperands() docs.
  1010. static Constant *
  1011. getGetElementPtr(Type *Ty, Constant *C, ArrayRef<Constant *> IdxList,
  1012. bool InBounds = false,
  1013. std::optional<unsigned> InRangeIndex = std::nullopt,
  1014. Type *OnlyIfReducedTy = nullptr) {
  1015. return getGetElementPtr(
  1016. Ty, C, ArrayRef((Value *const *)IdxList.data(), IdxList.size()),
  1017. InBounds, InRangeIndex, OnlyIfReducedTy);
  1018. }
  1019. static Constant *
  1020. getGetElementPtr(Type *Ty, Constant *C, Constant *Idx, bool InBounds = false,
  1021. std::optional<unsigned> InRangeIndex = std::nullopt,
  1022. Type *OnlyIfReducedTy = nullptr) {
  1023. // This form of the function only exists to avoid ambiguous overload
  1024. // warnings about whether to convert Idx to ArrayRef<Constant *> or
  1025. // ArrayRef<Value *>.
  1026. return getGetElementPtr(Ty, C, cast<Value>(Idx), InBounds, InRangeIndex,
  1027. OnlyIfReducedTy);
  1028. }
  1029. static Constant *
  1030. getGetElementPtr(Type *Ty, Constant *C, ArrayRef<Value *> IdxList,
  1031. bool InBounds = false,
  1032. std::optional<unsigned> InRangeIndex = std::nullopt,
  1033. Type *OnlyIfReducedTy = nullptr);
  1034. /// Create an "inbounds" getelementptr. See the documentation for the
  1035. /// "inbounds" flag in LangRef.html for details.
  1036. static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
  1037. ArrayRef<Constant *> IdxList) {
  1038. return getGetElementPtr(Ty, C, IdxList, true);
  1039. }
  1040. static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
  1041. Constant *Idx) {
  1042. // This form of the function only exists to avoid ambiguous overload
  1043. // warnings about whether to convert Idx to ArrayRef<Constant *> or
  1044. // ArrayRef<Value *>.
  1045. return getGetElementPtr(Ty, C, Idx, true);
  1046. }
  1047. static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
  1048. ArrayRef<Value *> IdxList) {
  1049. return getGetElementPtr(Ty, C, IdxList, true);
  1050. }
  1051. static Constant *getExtractElement(Constant *Vec, Constant *Idx,
  1052. Type *OnlyIfReducedTy = nullptr);
  1053. static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx,
  1054. Type *OnlyIfReducedTy = nullptr);
  1055. static Constant *getShuffleVector(Constant *V1, Constant *V2,
  1056. ArrayRef<int> Mask,
  1057. Type *OnlyIfReducedTy = nullptr);
  1058. /// Return the opcode at the root of this constant expression
  1059. unsigned getOpcode() const { return getSubclassDataFromValue(); }
  1060. /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or
  1061. /// FCMP constant expression.
  1062. unsigned getPredicate() const;
  1063. /// Assert that this is a shufflevector and return the mask. See class
  1064. /// ShuffleVectorInst for a description of the mask representation.
  1065. ArrayRef<int> getShuffleMask() const;
  1066. /// Assert that this is a shufflevector and return the mask.
  1067. ///
  1068. /// TODO: This is a temporary hack until we update the bitcode format for
  1069. /// shufflevector.
  1070. Constant *getShuffleMaskForBitcode() const;
  1071. /// Return a string representation for an opcode.
  1072. const char *getOpcodeName() const;
  1073. /// This returns the current constant expression with the operands replaced
  1074. /// with the specified values. The specified array must have the same number
  1075. /// of operands as our current one.
  1076. Constant *getWithOperands(ArrayRef<Constant *> Ops) const {
  1077. return getWithOperands(Ops, getType());
  1078. }
  1079. /// Get the current expression with the operands replaced.
  1080. ///
  1081. /// Return the current constant expression with the operands replaced with \c
  1082. /// Ops and the type with \c Ty. The new operands must have the same number
  1083. /// as the current ones.
  1084. ///
  1085. /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something
  1086. /// gets constant-folded, the type changes, or the expression is otherwise
  1087. /// canonicalized. This parameter should almost always be \c false.
  1088. Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
  1089. bool OnlyIfReduced = false,
  1090. Type *SrcTy = nullptr) const;
  1091. /// Returns an Instruction which implements the same operation as this
  1092. /// ConstantExpr. If \p InsertBefore is not null, the new instruction is
  1093. /// inserted before it, otherwise it is not inserted into any basic block.
  1094. ///
  1095. /// A better approach to this could be to have a constructor for Instruction
  1096. /// which would take a ConstantExpr parameter, but that would have spread
  1097. /// implementation details of ConstantExpr outside of Constants.cpp, which
  1098. /// would make it harder to remove ConstantExprs altogether.
  1099. Instruction *getAsInstruction(Instruction *InsertBefore = nullptr) const;
  1100. /// Whether creating a constant expression for this binary operator is
  1101. /// desirable.
  1102. static bool isDesirableBinOp(unsigned Opcode);
  1103. /// Whether creating a constant expression for this binary operator is
  1104. /// supported.
  1105. static bool isSupportedBinOp(unsigned Opcode);
  1106. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  1107. static bool classof(const Value *V) {
  1108. return V->getValueID() == ConstantExprVal;
  1109. }
  1110. private:
  1111. // Shadow Value::setValueSubclassData with a private forwarding method so that
  1112. // subclasses cannot accidentally use it.
  1113. void setValueSubclassData(unsigned short D) {
  1114. Value::setValueSubclassData(D);
  1115. }
  1116. };
  1117. template <>
  1118. struct OperandTraits<ConstantExpr>
  1119. : public VariadicOperandTraits<ConstantExpr, 1> {};
  1120. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)
  1121. //===----------------------------------------------------------------------===//
  1122. /// 'undef' values are things that do not have specified contents.
  1123. /// These are used for a variety of purposes, including global variable
  1124. /// initializers and operands to instructions. 'undef' values can occur with
  1125. /// any first-class type.
  1126. ///
  1127. /// Undef values aren't exactly constants; if they have multiple uses, they
  1128. /// can appear to have different bit patterns at each use. See
  1129. /// LangRef.html#undefvalues for details.
  1130. ///
  1131. class UndefValue : public ConstantData {
  1132. friend class Constant;
  1133. explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {}
  1134. void destroyConstantImpl();
  1135. protected:
  1136. explicit UndefValue(Type *T, ValueTy vty) : ConstantData(T, vty) {}
  1137. public:
  1138. UndefValue(const UndefValue &) = delete;
  1139. /// Static factory methods - Return an 'undef' object of the specified type.
  1140. static UndefValue *get(Type *T);
  1141. /// If this Undef has array or vector type, return a undef with the right
  1142. /// element type.
  1143. UndefValue *getSequentialElement() const;
  1144. /// If this undef has struct type, return a undef with the right element type
  1145. /// for the specified element.
  1146. UndefValue *getStructElement(unsigned Elt) const;
  1147. /// Return an undef of the right value for the specified GEP index if we can,
  1148. /// otherwise return null (e.g. if C is a ConstantExpr).
  1149. UndefValue *getElementValue(Constant *C) const;
  1150. /// Return an undef of the right value for the specified GEP index.
  1151. UndefValue *getElementValue(unsigned Idx) const;
  1152. /// Return the number of elements in the array, vector, or struct.
  1153. unsigned getNumElements() const;
  1154. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  1155. static bool classof(const Value *V) {
  1156. return V->getValueID() == UndefValueVal ||
  1157. V->getValueID() == PoisonValueVal;
  1158. }
  1159. };
  1160. //===----------------------------------------------------------------------===//
  1161. /// In order to facilitate speculative execution, many instructions do not
  1162. /// invoke immediate undefined behavior when provided with illegal operands,
  1163. /// and return a poison value instead.
  1164. ///
  1165. /// see LangRef.html#poisonvalues for details.
  1166. ///
  1167. class PoisonValue final : public UndefValue {
  1168. friend class Constant;
  1169. explicit PoisonValue(Type *T) : UndefValue(T, PoisonValueVal) {}
  1170. void destroyConstantImpl();
  1171. public:
  1172. PoisonValue(const PoisonValue &) = delete;
  1173. /// Static factory methods - Return an 'poison' object of the specified type.
  1174. static PoisonValue *get(Type *T);
  1175. /// If this poison has array or vector type, return a poison with the right
  1176. /// element type.
  1177. PoisonValue *getSequentialElement() const;
  1178. /// If this poison has struct type, return a poison with the right element
  1179. /// type for the specified element.
  1180. PoisonValue *getStructElement(unsigned Elt) const;
  1181. /// Return an poison of the right value for the specified GEP index if we can,
  1182. /// otherwise return null (e.g. if C is a ConstantExpr).
  1183. PoisonValue *getElementValue(Constant *C) const;
  1184. /// Return an poison of the right value for the specified GEP index.
  1185. PoisonValue *getElementValue(unsigned Idx) const;
  1186. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  1187. static bool classof(const Value *V) {
  1188. return V->getValueID() == PoisonValueVal;
  1189. }
  1190. };
  1191. } // end namespace llvm
  1192. #endif // LLVM_IR_CONSTANTS_H
  1193. #ifdef __GNUC__
  1194. #pragma GCC diagnostic pop
  1195. #endif