Constants.h 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  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/None.h"
  30. #include "llvm/ADT/Optional.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. #include "llvm/ADT/StringRef.h"
  33. #include "llvm/IR/Constant.h"
  34. #include "llvm/IR/DerivedTypes.h"
  35. #include "llvm/IR/OperandTraits.h"
  36. #include "llvm/IR/User.h"
  37. #include "llvm/IR/Value.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include <cassert>
  42. #include <cstddef>
  43. #include <cstdint>
  44. namespace llvm {
  45. template <class ConstantClass> struct ConstantAggrKeyType;
  46. /// Base class for constants with no operands.
  47. ///
  48. /// These constants have no operands; they represent their data directly.
  49. /// Since they can be in use by unrelated modules (and are never based on
  50. /// GlobalValues), it never makes sense to RAUW them.
  51. class ConstantData : public Constant {
  52. friend class Constant;
  53. Value *handleOperandChangeImpl(Value *From, Value *To) {
  54. llvm_unreachable("Constant data does not have operands!");
  55. }
  56. protected:
  57. explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {}
  58. void *operator new(size_t S) { return User::operator new(S, 0); }
  59. public:
  60. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  61. ConstantData(const ConstantData &) = delete;
  62. /// Methods to support type inquiry through isa, cast, and dyn_cast.
  63. static bool classof(const Value *V) {
  64. return V->getValueID() >= ConstantDataFirstVal &&
  65. V->getValueID() <= ConstantDataLastVal;
  66. }
  67. };
  68. //===----------------------------------------------------------------------===//
  69. /// This is the shared class of boolean and integer constants. This class
  70. /// represents both boolean and integral constants.
  71. /// Class for constant integers.
  72. class ConstantInt final : public ConstantData {
  73. friend class Constant;
  74. APInt Val;
  75. ConstantInt(IntegerType *Ty, const APInt &V);
  76. void destroyConstantImpl();
  77. public:
  78. ConstantInt(const ConstantInt &) = delete;
  79. static ConstantInt *getTrue(LLVMContext &Context);
  80. static ConstantInt *getFalse(LLVMContext &Context);
  81. static ConstantInt *getBool(LLVMContext &Context, bool V);
  82. static Constant *getTrue(Type *Ty);
  83. static Constant *getFalse(Type *Ty);
  84. static Constant *getBool(Type *Ty, bool V);
  85. /// If Ty is a vector type, return a Constant with a splat of the given
  86. /// value. Otherwise return a ConstantInt for the given value.
  87. static Constant *get(Type *Ty, uint64_t V, bool IsSigned = false);
  88. /// Return a ConstantInt with the specified integer value for the specified
  89. /// type. If the type is wider than 64 bits, the value will be zero-extended
  90. /// to fit the type, unless IsSigned is true, in which case the value will
  91. /// be interpreted as a 64-bit signed integer and sign-extended to fit
  92. /// the type.
  93. /// Get a ConstantInt for a specific value.
  94. static ConstantInt *get(IntegerType *Ty, uint64_t V, bool IsSigned = false);
  95. /// Return a ConstantInt with the specified value for the specified type. The
  96. /// value V will be canonicalized to a an unsigned APInt. Accessing it with
  97. /// either getSExtValue() or getZExtValue() will yield a correctly sized and
  98. /// signed value for the type Ty.
  99. /// Get a ConstantInt for a specific signed value.
  100. static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
  101. static Constant *getSigned(Type *Ty, int64_t V);
  102. /// Return a ConstantInt with the specified value and an implied Type. The
  103. /// type is the integer type that corresponds to the bit width of the value.
  104. static ConstantInt *get(LLVMContext &Context, const APInt &V);
  105. /// Return a ConstantInt constructed from the string strStart with the given
  106. /// radix.
  107. static ConstantInt *get(IntegerType *Ty, StringRef Str, uint8_t Radix);
  108. /// If Ty is a vector type, return a Constant with a splat of the given
  109. /// value. Otherwise return a ConstantInt for the given value.
  110. static Constant *get(Type *Ty, const APInt &V);
  111. /// Return the constant as an APInt value reference. This allows clients to
  112. /// obtain a full-precision copy of the value.
  113. /// Return the constant's value.
  114. inline const APInt &getValue() const { return Val; }
  115. /// getBitWidth - Return the bitwidth of this constant.
  116. unsigned getBitWidth() const { return Val.getBitWidth(); }
  117. /// Return the constant as a 64-bit unsigned integer value after it
  118. /// has been zero extended as appropriate for the type of this constant. Note
  119. /// that this method can assert if the value does not fit in 64 bits.
  120. /// Return the zero extended value.
  121. inline uint64_t getZExtValue() const { return Val.getZExtValue(); }
  122. /// Return the constant as a 64-bit integer value after it has been sign
  123. /// extended as appropriate for the type of this constant. Note that
  124. /// this method can assert if the value does not fit in 64 bits.
  125. /// Return the sign extended value.
  126. inline int64_t getSExtValue() const { return Val.getSExtValue(); }
  127. /// Return the constant as an llvm::MaybeAlign.
  128. /// Note that this method can assert if the value does not fit in 64 bits or
  129. /// is not a power of two.
  130. inline MaybeAlign getMaybeAlignValue() const {
  131. return MaybeAlign(getZExtValue());
  132. }
  133. /// Return the constant as an llvm::Align, interpreting `0` as `Align(1)`.
  134. /// Note that this method can assert if the value does not fit in 64 bits or
  135. /// is not a power of two.
  136. inline Align getAlignValue() const {
  137. return getMaybeAlignValue().valueOrOne();
  138. }
  139. /// A helper method that can be used to determine if the constant contained
  140. /// within is equal to a constant. This only works for very small values,
  141. /// because this is all that can be represented with all types.
  142. /// Determine if this constant's value is same as an unsigned char.
  143. bool equalsInt(uint64_t V) const { return Val == V; }
  144. /// getType - Specialize the getType() method to always return an IntegerType,
  145. /// which reduces the amount of casting needed in parts of the compiler.
  146. ///
  147. inline IntegerType *getType() const {
  148. return cast<IntegerType>(Value::getType());
  149. }
  150. /// This static method returns true if the type Ty is big enough to
  151. /// represent the value V. This can be used to avoid having the get method
  152. /// assert when V is larger than Ty can represent. Note that there are two
  153. /// versions of this method, one for unsigned and one for signed integers.
  154. /// Although ConstantInt canonicalizes everything to an unsigned integer,
  155. /// the signed version avoids callers having to convert a signed quantity
  156. /// to the appropriate unsigned type before calling the method.
  157. /// @returns true if V is a valid value for type Ty
  158. /// Determine if the value is in range for the given type.
  159. static bool isValueValidForType(Type *Ty, uint64_t V);
  160. static bool isValueValidForType(Type *Ty, int64_t V);
  161. bool isNegative() const { return Val.isNegative(); }
  162. /// This is just a convenience method to make client code smaller for a
  163. /// common code. It also correctly performs the comparison without the
  164. /// potential for an assertion from getZExtValue().
  165. bool isZero() const { return Val.isZero(); }
  166. /// This is just a convenience method to make client code smaller for a
  167. /// common case. It also correctly performs the comparison without the
  168. /// potential for an assertion from getZExtValue().
  169. /// Determine if the value is one.
  170. bool isOne() const { return Val.isOne(); }
  171. /// This function will return true iff every bit in this constant is set
  172. /// to true.
  173. /// @returns true iff this constant's bits are all set to true.
  174. /// Determine if the value is all ones.
  175. bool isMinusOne() const { return Val.isAllOnes(); }
  176. /// This function will return true iff this constant represents the largest
  177. /// value that may be represented by the constant's type.
  178. /// @returns true iff this is the largest value that may be represented
  179. /// by this type.
  180. /// Determine if the value is maximal.
  181. bool isMaxValue(bool IsSigned) const {
  182. if (IsSigned)
  183. return Val.isMaxSignedValue();
  184. else
  185. return Val.isMaxValue();
  186. }
  187. /// This function will return true iff this constant represents the smallest
  188. /// value that may be represented by this constant's type.
  189. /// @returns true if this is the smallest value that may be represented by
  190. /// this type.
  191. /// Determine if the value is minimal.
  192. bool isMinValue(bool IsSigned) const {
  193. if (IsSigned)
  194. return Val.isMinSignedValue();
  195. else
  196. return Val.isMinValue();
  197. }
  198. /// This function will return true iff this constant represents a value with
  199. /// active bits bigger than 64 bits or a value greater than the given uint64_t
  200. /// value.
  201. /// @returns true iff this constant is greater or equal to the given number.
  202. /// Determine if the value is greater or equal to the given number.
  203. bool uge(uint64_t Num) const { return Val.uge(Num); }
  204. /// getLimitedValue - If the value is smaller than the specified limit,
  205. /// return it, otherwise return the limit value. This causes the value
  206. /// to saturate to the limit.
  207. /// @returns the min of the value of the constant and the specified value
  208. /// Get the constant's value with a saturation limit
  209. uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
  210. return Val.getLimitedValue(Limit);
  211. }
  212. /// Methods to support type inquiry through isa, cast, and dyn_cast.
  213. static bool classof(const Value *V) {
  214. return V->getValueID() == ConstantIntVal;
  215. }
  216. };
  217. //===----------------------------------------------------------------------===//
  218. /// ConstantFP - Floating Point Values [float, double]
  219. ///
  220. class ConstantFP final : public ConstantData {
  221. friend class Constant;
  222. APFloat Val;
  223. ConstantFP(Type *Ty, const APFloat &V);
  224. void destroyConstantImpl();
  225. public:
  226. ConstantFP(const ConstantFP &) = delete;
  227. /// Floating point negation must be implemented with f(x) = -0.0 - x. This
  228. /// method returns the negative zero constant for floating point or vector
  229. /// floating point types; for all other types, it returns the null value.
  230. static Constant *getZeroValueForNegation(Type *Ty);
  231. /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP,
  232. /// for the specified value in the specified type. This should only be used
  233. /// for simple constant values like 2.0/1.0 etc, that are known-valid both as
  234. /// host double and as the target format.
  235. static Constant *get(Type *Ty, double V);
  236. /// If Ty is a vector type, return a Constant with a splat of the given
  237. /// value. Otherwise return a ConstantFP for the given value.
  238. static Constant *get(Type *Ty, const APFloat &V);
  239. static Constant *get(Type *Ty, StringRef Str);
  240. static ConstantFP *get(LLVMContext &Context, const APFloat &V);
  241. static Constant *getNaN(Type *Ty, bool Negative = false,
  242. uint64_t Payload = 0);
  243. static Constant *getQNaN(Type *Ty, bool Negative = false,
  244. APInt *Payload = nullptr);
  245. static Constant *getSNaN(Type *Ty, bool Negative = false,
  246. APInt *Payload = nullptr);
  247. static Constant *getNegativeZero(Type *Ty);
  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, makeArrayRef(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. /// The address of a basic block.
  694. ///
  695. class BlockAddress final : public Constant {
  696. friend class Constant;
  697. BlockAddress(Function *F, BasicBlock *BB);
  698. void *operator new(size_t S) { return User::operator new(S, 2); }
  699. void destroyConstantImpl();
  700. Value *handleOperandChangeImpl(Value *From, Value *To);
  701. public:
  702. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  703. /// Return a BlockAddress for the specified function and basic block.
  704. static BlockAddress *get(Function *F, BasicBlock *BB);
  705. /// Return a BlockAddress for the specified basic block. The basic
  706. /// block must be embedded into a function.
  707. static BlockAddress *get(BasicBlock *BB);
  708. /// Lookup an existing \c BlockAddress constant for the given BasicBlock.
  709. ///
  710. /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
  711. static BlockAddress *lookup(const BasicBlock *BB);
  712. /// Transparently provide more efficient getOperand methods.
  713. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  714. Function *getFunction() const { return (Function *)Op<0>().get(); }
  715. BasicBlock *getBasicBlock() const { return (BasicBlock *)Op<1>().get(); }
  716. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  717. static bool classof(const Value *V) {
  718. return V->getValueID() == BlockAddressVal;
  719. }
  720. };
  721. template <>
  722. struct OperandTraits<BlockAddress>
  723. : public FixedNumOperandTraits<BlockAddress, 2> {};
  724. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
  725. /// Wrapper for a function that represents a value that
  726. /// functionally represents the original function. This can be a function,
  727. /// global alias to a function, or an ifunc.
  728. class DSOLocalEquivalent final : public Constant {
  729. friend class Constant;
  730. DSOLocalEquivalent(GlobalValue *GV);
  731. void *operator new(size_t S) { return User::operator new(S, 1); }
  732. void destroyConstantImpl();
  733. Value *handleOperandChangeImpl(Value *From, Value *To);
  734. public:
  735. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  736. /// Return a DSOLocalEquivalent for the specified global value.
  737. static DSOLocalEquivalent *get(GlobalValue *GV);
  738. /// Transparently provide more efficient getOperand methods.
  739. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  740. GlobalValue *getGlobalValue() const {
  741. return cast<GlobalValue>(Op<0>().get());
  742. }
  743. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  744. static bool classof(const Value *V) {
  745. return V->getValueID() == DSOLocalEquivalentVal;
  746. }
  747. };
  748. template <>
  749. struct OperandTraits<DSOLocalEquivalent>
  750. : public FixedNumOperandTraits<DSOLocalEquivalent, 1> {};
  751. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(DSOLocalEquivalent, Value)
  752. /// Wrapper for a value that won't be replaced with a CFI jump table
  753. /// pointer in LowerTypeTestsModule.
  754. class NoCFIValue final : public Constant {
  755. friend class Constant;
  756. NoCFIValue(GlobalValue *GV);
  757. void *operator new(size_t S) { return User::operator new(S, 1); }
  758. void destroyConstantImpl();
  759. Value *handleOperandChangeImpl(Value *From, Value *To);
  760. public:
  761. /// Return a NoCFIValue for the specified function.
  762. static NoCFIValue *get(GlobalValue *GV);
  763. /// Transparently provide more efficient getOperand methods.
  764. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  765. GlobalValue *getGlobalValue() const {
  766. return cast<GlobalValue>(Op<0>().get());
  767. }
  768. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  769. static bool classof(const Value *V) {
  770. return V->getValueID() == NoCFIValueVal;
  771. }
  772. };
  773. template <>
  774. struct OperandTraits<NoCFIValue> : public FixedNumOperandTraits<NoCFIValue, 1> {
  775. };
  776. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(NoCFIValue, Value)
  777. //===----------------------------------------------------------------------===//
  778. /// A constant value that is initialized with an expression using
  779. /// other constant values.
  780. ///
  781. /// This class uses the standard Instruction opcodes to define the various
  782. /// constant expressions. The Opcode field for the ConstantExpr class is
  783. /// maintained in the Value::SubclassData field.
  784. class ConstantExpr : public Constant {
  785. friend struct ConstantExprKeyType;
  786. friend class Constant;
  787. void destroyConstantImpl();
  788. Value *handleOperandChangeImpl(Value *From, Value *To);
  789. protected:
  790. ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
  791. : Constant(ty, ConstantExprVal, Ops, NumOps) {
  792. // Operation type (an Instruction opcode) is stored as the SubclassData.
  793. setValueSubclassData(Opcode);
  794. }
  795. ~ConstantExpr() = default;
  796. public:
  797. // Static methods to construct a ConstantExpr of different kinds. Note that
  798. // these methods may return a object that is not an instance of the
  799. // ConstantExpr class, because they will attempt to fold the constant
  800. // expression into something simpler if possible.
  801. /// getAlignOf constant expr - computes the alignment of a type in a target
  802. /// independent way (Note: the return type is an i64).
  803. static Constant *getAlignOf(Type *Ty);
  804. /// getSizeOf constant expr - computes the (alloc) size of a type (in
  805. /// address-units, not bits) in a target independent way (Note: the return
  806. /// type is an i64).
  807. ///
  808. static Constant *getSizeOf(Type *Ty);
  809. /// getOffsetOf constant expr - computes the offset of a struct field in a
  810. /// target independent way (Note: the return type is an i64).
  811. ///
  812. static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
  813. /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
  814. /// which supports any aggregate type, and any Constant index.
  815. ///
  816. static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
  817. static Constant *getNeg(Constant *C, bool HasNUW = false,
  818. bool HasNSW = false);
  819. static Constant *getFNeg(Constant *C);
  820. static Constant *getNot(Constant *C);
  821. static Constant *getAdd(Constant *C1, Constant *C2, bool HasNUW = false,
  822. bool HasNSW = false);
  823. static Constant *getFAdd(Constant *C1, Constant *C2);
  824. static Constant *getSub(Constant *C1, Constant *C2, bool HasNUW = false,
  825. bool HasNSW = false);
  826. static Constant *getFSub(Constant *C1, Constant *C2);
  827. static Constant *getMul(Constant *C1, Constant *C2, bool HasNUW = false,
  828. bool HasNSW = false);
  829. static Constant *getFMul(Constant *C1, Constant *C2);
  830. static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
  831. static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
  832. static Constant *getFDiv(Constant *C1, Constant *C2);
  833. static Constant *getURem(Constant *C1, Constant *C2);
  834. static Constant *getSRem(Constant *C1, Constant *C2);
  835. static Constant *getFRem(Constant *C1, Constant *C2);
  836. static Constant *getAnd(Constant *C1, Constant *C2);
  837. static Constant *getOr(Constant *C1, Constant *C2);
  838. static Constant *getXor(Constant *C1, Constant *C2);
  839. static Constant *getUMin(Constant *C1, Constant *C2);
  840. static Constant *getShl(Constant *C1, Constant *C2, bool HasNUW = false,
  841. bool HasNSW = false);
  842. static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
  843. static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
  844. static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  845. static Constant *getSExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  846. static Constant *getZExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  847. static Constant *getFPTrunc(Constant *C, Type *Ty,
  848. bool OnlyIfReduced = false);
  849. static Constant *getFPExtend(Constant *C, Type *Ty,
  850. bool OnlyIfReduced = false);
  851. static Constant *getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  852. static Constant *getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  853. static Constant *getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  854. static Constant *getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
  855. static Constant *getPtrToInt(Constant *C, Type *Ty,
  856. bool OnlyIfReduced = false);
  857. static Constant *getIntToPtr(Constant *C, Type *Ty,
  858. bool OnlyIfReduced = false);
  859. static Constant *getBitCast(Constant *C, Type *Ty,
  860. bool OnlyIfReduced = false);
  861. static Constant *getAddrSpaceCast(Constant *C, Type *Ty,
  862. bool OnlyIfReduced = false);
  863. static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
  864. static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
  865. static Constant *getNSWAdd(Constant *C1, Constant *C2) {
  866. return getAdd(C1, C2, false, true);
  867. }
  868. static Constant *getNUWAdd(Constant *C1, Constant *C2) {
  869. return getAdd(C1, C2, true, false);
  870. }
  871. static Constant *getNSWSub(Constant *C1, Constant *C2) {
  872. return getSub(C1, C2, false, true);
  873. }
  874. static Constant *getNUWSub(Constant *C1, Constant *C2) {
  875. return getSub(C1, C2, true, false);
  876. }
  877. static Constant *getNSWMul(Constant *C1, Constant *C2) {
  878. return getMul(C1, C2, false, true);
  879. }
  880. static Constant *getNUWMul(Constant *C1, Constant *C2) {
  881. return getMul(C1, C2, true, false);
  882. }
  883. static Constant *getNSWShl(Constant *C1, Constant *C2) {
  884. return getShl(C1, C2, false, true);
  885. }
  886. static Constant *getNUWShl(Constant *C1, Constant *C2) {
  887. return getShl(C1, C2, true, false);
  888. }
  889. static Constant *getExactSDiv(Constant *C1, Constant *C2) {
  890. return getSDiv(C1, C2, true);
  891. }
  892. static Constant *getExactUDiv(Constant *C1, Constant *C2) {
  893. return getUDiv(C1, C2, true);
  894. }
  895. static Constant *getExactAShr(Constant *C1, Constant *C2) {
  896. return getAShr(C1, C2, true);
  897. }
  898. static Constant *getExactLShr(Constant *C1, Constant *C2) {
  899. return getLShr(C1, C2, true);
  900. }
  901. /// If C is a scalar/fixed width vector of known powers of 2, then this
  902. /// function returns a new scalar/fixed width vector obtained from logBase2
  903. /// of C. Undef vector elements are set to zero.
  904. /// Return a null pointer otherwise.
  905. static Constant *getExactLogBase2(Constant *C);
  906. /// Return the identity constant for a binary opcode.
  907. /// The identity constant C is defined as X op C = X and C op X = X for every
  908. /// X when the binary operation is commutative. If the binop is not
  909. /// commutative, callers can acquire the operand 1 identity constant by
  910. /// setting AllowRHSConstant to true. For example, any shift has a zero
  911. /// identity constant for operand 1: X shift 0 = X.
  912. /// Return nullptr if the operator does not have an identity constant.
  913. static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty,
  914. bool AllowRHSConstant = false);
  915. /// Return the absorbing element for the given binary
  916. /// operation, i.e. a constant C such that X op C = C and C op X = C for
  917. /// every X. For example, this returns zero for integer multiplication.
  918. /// It returns null if the operator doesn't have an absorbing element.
  919. static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
  920. /// Transparently provide more efficient getOperand methods.
  921. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
  922. /// Convenience function for getting a Cast operation.
  923. ///
  924. /// \param ops The opcode for the conversion
  925. /// \param C The constant to be converted
  926. /// \param Ty The type to which the constant is converted
  927. /// \param OnlyIfReduced see \a getWithOperands() docs.
  928. static Constant *getCast(unsigned ops, Constant *C, Type *Ty,
  929. bool OnlyIfReduced = false);
  930. // Create a ZExt or BitCast cast constant expression
  931. static Constant *
  932. getZExtOrBitCast(Constant *C, ///< The constant to zext or bitcast
  933. Type *Ty ///< The type to zext or bitcast C to
  934. );
  935. // Create a SExt or BitCast cast constant expression
  936. static Constant *
  937. getSExtOrBitCast(Constant *C, ///< The constant to sext or bitcast
  938. Type *Ty ///< The type to sext or bitcast C to
  939. );
  940. // Create a Trunc or BitCast cast constant expression
  941. static Constant *
  942. getTruncOrBitCast(Constant *C, ///< The constant to trunc or bitcast
  943. Type *Ty ///< The type to trunc or bitcast C to
  944. );
  945. /// Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
  946. /// expression.
  947. static Constant *
  948. getPointerCast(Constant *C, ///< The pointer value to be casted (operand 0)
  949. Type *Ty ///< The type to which cast should be made
  950. );
  951. /// Create a BitCast or AddrSpaceCast for a pointer type depending on
  952. /// the address space.
  953. static Constant *getPointerBitCastOrAddrSpaceCast(
  954. Constant *C, ///< The constant to addrspacecast or bitcast
  955. Type *Ty ///< The type to bitcast or addrspacecast C to
  956. );
  957. /// Create a ZExt, Bitcast or Trunc for integer -> integer casts
  958. static Constant *
  959. getIntegerCast(Constant *C, ///< The integer constant to be casted
  960. Type *Ty, ///< The integer type to cast to
  961. bool IsSigned ///< Whether C should be treated as signed or not
  962. );
  963. /// Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
  964. static Constant *getFPCast(Constant *C, ///< The integer constant to be casted
  965. Type *Ty ///< The integer type to cast to
  966. );
  967. /// Return true if this is a convert constant expression
  968. bool isCast() const;
  969. /// Return true if this is a compare constant expression
  970. bool isCompare() const;
  971. /// Return true if this is an insertvalue or extractvalue expression,
  972. /// and the getIndices() method may be used.
  973. bool hasIndices() const;
  974. /// Select constant expr
  975. ///
  976. /// \param OnlyIfReducedTy see \a getWithOperands() docs.
  977. static Constant *getSelect(Constant *C, Constant *V1, Constant *V2,
  978. Type *OnlyIfReducedTy = nullptr);
  979. /// get - Return a unary operator constant expression,
  980. /// folding if possible.
  981. ///
  982. /// \param OnlyIfReducedTy see \a getWithOperands() docs.
  983. static Constant *get(unsigned Opcode, Constant *C1, unsigned Flags = 0,
  984. Type *OnlyIfReducedTy = nullptr);
  985. /// get - Return a binary or shift operator constant expression,
  986. /// folding if possible.
  987. ///
  988. /// \param OnlyIfReducedTy see \a getWithOperands() docs.
  989. static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
  990. unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr);
  991. /// Return an ICmp or FCmp comparison operator constant expression.
  992. ///
  993. /// \param OnlyIfReduced see \a getWithOperands() docs.
  994. static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2,
  995. bool OnlyIfReduced = false);
  996. /// get* - Return some common constants without having to
  997. /// specify the full Instruction::OPCODE identifier.
  998. ///
  999. static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS,
  1000. bool OnlyIfReduced = false);
  1001. static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS,
  1002. bool OnlyIfReduced = false);
  1003. /// Getelementptr form. Value* is only accepted for convenience;
  1004. /// all elements must be Constants.
  1005. ///
  1006. /// \param InRangeIndex the inrange index if present or None.
  1007. /// \param OnlyIfReducedTy see \a getWithOperands() docs.
  1008. static Constant *getGetElementPtr(Type *Ty, Constant *C,
  1009. ArrayRef<Constant *> IdxList,
  1010. bool InBounds = false,
  1011. Optional<unsigned> InRangeIndex = None,
  1012. Type *OnlyIfReducedTy = nullptr) {
  1013. return getGetElementPtr(
  1014. Ty, C, makeArrayRef((Value *const *)IdxList.data(), IdxList.size()),
  1015. InBounds, InRangeIndex, OnlyIfReducedTy);
  1016. }
  1017. static Constant *getGetElementPtr(Type *Ty, Constant *C, Constant *Idx,
  1018. bool InBounds = false,
  1019. Optional<unsigned> InRangeIndex = None,
  1020. Type *OnlyIfReducedTy = nullptr) {
  1021. // This form of the function only exists to avoid ambiguous overload
  1022. // warnings about whether to convert Idx to ArrayRef<Constant *> or
  1023. // ArrayRef<Value *>.
  1024. return getGetElementPtr(Ty, C, cast<Value>(Idx), InBounds, InRangeIndex,
  1025. OnlyIfReducedTy);
  1026. }
  1027. static Constant *getGetElementPtr(Type *Ty, Constant *C,
  1028. ArrayRef<Value *> IdxList,
  1029. bool InBounds = false,
  1030. Optional<unsigned> InRangeIndex = None,
  1031. Type *OnlyIfReducedTy = nullptr);
  1032. /// Create an "inbounds" getelementptr. See the documentation for the
  1033. /// "inbounds" flag in LangRef.html for details.
  1034. static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
  1035. ArrayRef<Constant *> IdxList) {
  1036. return getGetElementPtr(Ty, C, IdxList, true);
  1037. }
  1038. static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
  1039. Constant *Idx) {
  1040. // This form of the function only exists to avoid ambiguous overload
  1041. // warnings about whether to convert Idx to ArrayRef<Constant *> or
  1042. // ArrayRef<Value *>.
  1043. return getGetElementPtr(Ty, C, Idx, true);
  1044. }
  1045. static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
  1046. ArrayRef<Value *> IdxList) {
  1047. return getGetElementPtr(Ty, C, IdxList, true);
  1048. }
  1049. static Constant *getExtractElement(Constant *Vec, Constant *Idx,
  1050. Type *OnlyIfReducedTy = nullptr);
  1051. static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx,
  1052. Type *OnlyIfReducedTy = nullptr);
  1053. static Constant *getShuffleVector(Constant *V1, Constant *V2,
  1054. ArrayRef<int> Mask,
  1055. Type *OnlyIfReducedTy = nullptr);
  1056. static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
  1057. Type *OnlyIfReducedTy = nullptr);
  1058. static Constant *getInsertValue(Constant *Agg, Constant *Val,
  1059. ArrayRef<unsigned> Idxs,
  1060. Type *OnlyIfReducedTy = nullptr);
  1061. /// Return the opcode at the root of this constant expression
  1062. unsigned getOpcode() const { return getSubclassDataFromValue(); }
  1063. /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or
  1064. /// FCMP constant expression.
  1065. unsigned getPredicate() const;
  1066. /// Assert that this is an insertvalue or exactvalue
  1067. /// expression and return the list of indices.
  1068. ArrayRef<unsigned> getIndices() const;
  1069. /// Assert that this is a shufflevector and return the mask. See class
  1070. /// ShuffleVectorInst for a description of the mask representation.
  1071. ArrayRef<int> getShuffleMask() const;
  1072. /// Assert that this is a shufflevector and return the mask.
  1073. ///
  1074. /// TODO: This is a temporary hack until we update the bitcode format for
  1075. /// shufflevector.
  1076. Constant *getShuffleMaskForBitcode() const;
  1077. /// Return a string representation for an opcode.
  1078. const char *getOpcodeName() const;
  1079. /// This returns the current constant expression with the operands replaced
  1080. /// with the specified values. The specified array must have the same number
  1081. /// of operands as our current one.
  1082. Constant *getWithOperands(ArrayRef<Constant *> Ops) const {
  1083. return getWithOperands(Ops, getType());
  1084. }
  1085. /// Get the current expression with the operands replaced.
  1086. ///
  1087. /// Return the current constant expression with the operands replaced with \c
  1088. /// Ops and the type with \c Ty. The new operands must have the same number
  1089. /// as the current ones.
  1090. ///
  1091. /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something
  1092. /// gets constant-folded, the type changes, or the expression is otherwise
  1093. /// canonicalized. This parameter should almost always be \c false.
  1094. Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
  1095. bool OnlyIfReduced = false,
  1096. Type *SrcTy = nullptr) const;
  1097. /// Returns an Instruction which implements the same operation as this
  1098. /// ConstantExpr. If \p InsertBefore is not null, the new instruction is
  1099. /// inserted before it, otherwise it is not inserted into any basic block.
  1100. ///
  1101. /// A better approach to this could be to have a constructor for Instruction
  1102. /// which would take a ConstantExpr parameter, but that would have spread
  1103. /// implementation details of ConstantExpr outside of Constants.cpp, which
  1104. /// would make it harder to remove ConstantExprs altogether.
  1105. Instruction *getAsInstruction(Instruction *InsertBefore = nullptr) const;
  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