IRBuilder.h 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- 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. // This file defines the IRBuilder class, which is used as a convenient way
  15. // to create LLVM instructions with a consistent and simplified interface.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_IRBUILDER_H
  19. #define LLVM_IR_IRBUILDER_H
  20. #include "llvm-c/Types.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/None.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/Constant.h"
  28. #include "llvm/IR/ConstantFolder.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/DebugInfoMetadata.h"
  32. #include "llvm/IR/DebugLoc.h"
  33. #include "llvm/IR/DerivedTypes.h"
  34. #include "llvm/IR/FPEnv.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/GlobalVariable.h"
  37. #include "llvm/IR/InstrTypes.h"
  38. #include "llvm/IR/Instruction.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/IR/Intrinsics.h"
  41. #include "llvm/IR/LLVMContext.h"
  42. #include "llvm/IR/Module.h"
  43. #include "llvm/IR/Operator.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/IR/Value.h"
  46. #include "llvm/IR/ValueHandle.h"
  47. #include "llvm/Support/AtomicOrdering.h"
  48. #include "llvm/Support/CBindingWrapping.h"
  49. #include "llvm/Support/Casting.h"
  50. #include <cassert>
  51. #include <cstdint>
  52. #include <functional>
  53. #include <utility>
  54. namespace llvm {
  55. class APInt;
  56. class Use;
  57. /// This provides the default implementation of the IRBuilder
  58. /// 'InsertHelper' method that is called whenever an instruction is created by
  59. /// IRBuilder and needs to be inserted.
  60. ///
  61. /// By default, this inserts the instruction at the insertion point.
  62. class IRBuilderDefaultInserter {
  63. public:
  64. virtual ~IRBuilderDefaultInserter();
  65. virtual void InsertHelper(Instruction *I, const Twine &Name,
  66. BasicBlock *BB,
  67. BasicBlock::iterator InsertPt) const {
  68. if (BB) BB->getInstList().insert(InsertPt, I);
  69. I->setName(Name);
  70. }
  71. };
  72. /// Provides an 'InsertHelper' that calls a user-provided callback after
  73. /// performing the default insertion.
  74. class IRBuilderCallbackInserter : public IRBuilderDefaultInserter {
  75. std::function<void(Instruction *)> Callback;
  76. public:
  77. virtual ~IRBuilderCallbackInserter();
  78. IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
  79. : Callback(std::move(Callback)) {}
  80. void InsertHelper(Instruction *I, const Twine &Name,
  81. BasicBlock *BB,
  82. BasicBlock::iterator InsertPt) const override {
  83. IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  84. Callback(I);
  85. }
  86. };
  87. /// Common base class shared among various IRBuilders.
  88. class IRBuilderBase {
  89. /// Pairs of (metadata kind, MDNode *) that should be added to all newly
  90. /// created instructions, like !dbg metadata.
  91. SmallVector<std::pair<unsigned, MDNode *>, 2> MetadataToCopy;
  92. /// Add or update the an entry (Kind, MD) to MetadataToCopy, if \p MD is not
  93. /// null. If \p MD is null, remove the entry with \p Kind.
  94. void AddOrRemoveMetadataToCopy(unsigned Kind, MDNode *MD) {
  95. if (!MD) {
  96. erase_if(MetadataToCopy, [Kind](const std::pair<unsigned, MDNode *> &KV) {
  97. return KV.first == Kind;
  98. });
  99. return;
  100. }
  101. for (auto &KV : MetadataToCopy)
  102. if (KV.first == Kind) {
  103. KV.second = MD;
  104. return;
  105. }
  106. MetadataToCopy.emplace_back(Kind, MD);
  107. }
  108. protected:
  109. BasicBlock *BB;
  110. BasicBlock::iterator InsertPt;
  111. LLVMContext &Context;
  112. const IRBuilderFolder &Folder;
  113. const IRBuilderDefaultInserter &Inserter;
  114. MDNode *DefaultFPMathTag;
  115. FastMathFlags FMF;
  116. bool IsFPConstrained;
  117. fp::ExceptionBehavior DefaultConstrainedExcept;
  118. RoundingMode DefaultConstrainedRounding;
  119. ArrayRef<OperandBundleDef> DefaultOperandBundles;
  120. public:
  121. IRBuilderBase(LLVMContext &context, const IRBuilderFolder &Folder,
  122. const IRBuilderDefaultInserter &Inserter,
  123. MDNode *FPMathTag, ArrayRef<OperandBundleDef> OpBundles)
  124. : Context(context), Folder(Folder), Inserter(Inserter),
  125. DefaultFPMathTag(FPMathTag), IsFPConstrained(false),
  126. DefaultConstrainedExcept(fp::ebStrict),
  127. DefaultConstrainedRounding(RoundingMode::Dynamic),
  128. DefaultOperandBundles(OpBundles) {
  129. ClearInsertionPoint();
  130. }
  131. /// Insert and return the specified instruction.
  132. template<typename InstTy>
  133. InstTy *Insert(InstTy *I, const Twine &Name = "") const {
  134. Inserter.InsertHelper(I, Name, BB, InsertPt);
  135. AddMetadataToInst(I);
  136. return I;
  137. }
  138. /// No-op overload to handle constants.
  139. Constant *Insert(Constant *C, const Twine& = "") const {
  140. return C;
  141. }
  142. Value *Insert(Value *V, const Twine &Name = "") const {
  143. if (Instruction *I = dyn_cast<Instruction>(V))
  144. return Insert(I, Name);
  145. assert(isa<Constant>(V));
  146. return V;
  147. }
  148. //===--------------------------------------------------------------------===//
  149. // Builder configuration methods
  150. //===--------------------------------------------------------------------===//
  151. /// Clear the insertion point: created instructions will not be
  152. /// inserted into a block.
  153. void ClearInsertionPoint() {
  154. BB = nullptr;
  155. InsertPt = BasicBlock::iterator();
  156. }
  157. BasicBlock *GetInsertBlock() const { return BB; }
  158. BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
  159. LLVMContext &getContext() const { return Context; }
  160. /// This specifies that created instructions should be appended to the
  161. /// end of the specified block.
  162. void SetInsertPoint(BasicBlock *TheBB) {
  163. BB = TheBB;
  164. InsertPt = BB->end();
  165. }
  166. /// This specifies that created instructions should be inserted before
  167. /// the specified instruction.
  168. void SetInsertPoint(Instruction *I) {
  169. BB = I->getParent();
  170. InsertPt = I->getIterator();
  171. assert(InsertPt != BB->end() && "Can't read debug loc from end()");
  172. SetCurrentDebugLocation(I->getDebugLoc());
  173. }
  174. /// This specifies that created instructions should be inserted at the
  175. /// specified point.
  176. void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
  177. BB = TheBB;
  178. InsertPt = IP;
  179. if (IP != TheBB->end())
  180. SetCurrentDebugLocation(IP->getDebugLoc());
  181. }
  182. /// Set location information used by debugging information.
  183. void SetCurrentDebugLocation(DebugLoc L) {
  184. AddOrRemoveMetadataToCopy(LLVMContext::MD_dbg, L.getAsMDNode());
  185. }
  186. /// Collect metadata with IDs \p MetadataKinds from \p Src which should be
  187. /// added to all created instructions. Entries present in MedataDataToCopy but
  188. /// not on \p Src will be dropped from MetadataToCopy.
  189. void CollectMetadataToCopy(Instruction *Src,
  190. ArrayRef<unsigned> MetadataKinds) {
  191. for (unsigned K : MetadataKinds)
  192. AddOrRemoveMetadataToCopy(K, Src->getMetadata(K));
  193. }
  194. /// Get location information used by debugging information.
  195. DebugLoc getCurrentDebugLocation() const {
  196. for (auto &KV : MetadataToCopy)
  197. if (KV.first == LLVMContext::MD_dbg)
  198. return {cast<DILocation>(KV.second)};
  199. return {};
  200. }
  201. /// If this builder has a current debug location, set it on the
  202. /// specified instruction.
  203. void SetInstDebugLocation(Instruction *I) const {
  204. for (const auto &KV : MetadataToCopy)
  205. if (KV.first == LLVMContext::MD_dbg) {
  206. I->setDebugLoc(DebugLoc(KV.second));
  207. return;
  208. }
  209. }
  210. /// Add all entries in MetadataToCopy to \p I.
  211. void AddMetadataToInst(Instruction *I) const {
  212. for (auto &KV : MetadataToCopy)
  213. I->setMetadata(KV.first, KV.second);
  214. }
  215. /// Get the return type of the current function that we're emitting
  216. /// into.
  217. Type *getCurrentFunctionReturnType() const;
  218. /// InsertPoint - A saved insertion point.
  219. class InsertPoint {
  220. BasicBlock *Block = nullptr;
  221. BasicBlock::iterator Point;
  222. public:
  223. /// Creates a new insertion point which doesn't point to anything.
  224. InsertPoint() = default;
  225. /// Creates a new insertion point at the given location.
  226. InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
  227. : Block(InsertBlock), Point(InsertPoint) {}
  228. /// Returns true if this insert point is set.
  229. bool isSet() const { return (Block != nullptr); }
  230. BasicBlock *getBlock() const { return Block; }
  231. BasicBlock::iterator getPoint() const { return Point; }
  232. };
  233. /// Returns the current insert point.
  234. InsertPoint saveIP() const {
  235. return InsertPoint(GetInsertBlock(), GetInsertPoint());
  236. }
  237. /// Returns the current insert point, clearing it in the process.
  238. InsertPoint saveAndClearIP() {
  239. InsertPoint IP(GetInsertBlock(), GetInsertPoint());
  240. ClearInsertionPoint();
  241. return IP;
  242. }
  243. /// Sets the current insert point to a previously-saved location.
  244. void restoreIP(InsertPoint IP) {
  245. if (IP.isSet())
  246. SetInsertPoint(IP.getBlock(), IP.getPoint());
  247. else
  248. ClearInsertionPoint();
  249. }
  250. /// Get the floating point math metadata being used.
  251. MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
  252. /// Get the flags to be applied to created floating point ops
  253. FastMathFlags getFastMathFlags() const { return FMF; }
  254. FastMathFlags &getFastMathFlags() { return FMF; }
  255. /// Clear the fast-math flags.
  256. void clearFastMathFlags() { FMF.clear(); }
  257. /// Set the floating point math metadata to be used.
  258. void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
  259. /// Set the fast-math flags to be used with generated fp-math operators
  260. void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
  261. /// Enable/Disable use of constrained floating point math. When
  262. /// enabled the CreateF<op>() calls instead create constrained
  263. /// floating point intrinsic calls. Fast math flags are unaffected
  264. /// by this setting.
  265. void setIsFPConstrained(bool IsCon) { IsFPConstrained = IsCon; }
  266. /// Query for the use of constrained floating point math
  267. bool getIsFPConstrained() { return IsFPConstrained; }
  268. /// Set the exception handling to be used with constrained floating point
  269. void setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept) {
  270. #ifndef NDEBUG
  271. Optional<StringRef> ExceptStr = convertExceptionBehaviorToStr(NewExcept);
  272. assert(ExceptStr.hasValue() && "Garbage strict exception behavior!");
  273. #endif
  274. DefaultConstrainedExcept = NewExcept;
  275. }
  276. /// Set the rounding mode handling to be used with constrained floating point
  277. void setDefaultConstrainedRounding(RoundingMode NewRounding) {
  278. #ifndef NDEBUG
  279. Optional<StringRef> RoundingStr = convertRoundingModeToStr(NewRounding);
  280. assert(RoundingStr.hasValue() && "Garbage strict rounding mode!");
  281. #endif
  282. DefaultConstrainedRounding = NewRounding;
  283. }
  284. /// Get the exception handling used with constrained floating point
  285. fp::ExceptionBehavior getDefaultConstrainedExcept() {
  286. return DefaultConstrainedExcept;
  287. }
  288. /// Get the rounding mode handling used with constrained floating point
  289. RoundingMode getDefaultConstrainedRounding() {
  290. return DefaultConstrainedRounding;
  291. }
  292. void setConstrainedFPFunctionAttr() {
  293. assert(BB && "Must have a basic block to set any function attributes!");
  294. Function *F = BB->getParent();
  295. if (!F->hasFnAttribute(Attribute::StrictFP)) {
  296. F->addFnAttr(Attribute::StrictFP);
  297. }
  298. }
  299. void setConstrainedFPCallAttr(CallBase *I) {
  300. I->addFnAttr(Attribute::StrictFP);
  301. }
  302. void setDefaultOperandBundles(ArrayRef<OperandBundleDef> OpBundles) {
  303. DefaultOperandBundles = OpBundles;
  304. }
  305. //===--------------------------------------------------------------------===//
  306. // RAII helpers.
  307. //===--------------------------------------------------------------------===//
  308. // RAII object that stores the current insertion point and restores it
  309. // when the object is destroyed. This includes the debug location.
  310. class InsertPointGuard {
  311. IRBuilderBase &Builder;
  312. AssertingVH<BasicBlock> Block;
  313. BasicBlock::iterator Point;
  314. DebugLoc DbgLoc;
  315. public:
  316. InsertPointGuard(IRBuilderBase &B)
  317. : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
  318. DbgLoc(B.getCurrentDebugLocation()) {}
  319. InsertPointGuard(const InsertPointGuard &) = delete;
  320. InsertPointGuard &operator=(const InsertPointGuard &) = delete;
  321. ~InsertPointGuard() {
  322. Builder.restoreIP(InsertPoint(Block, Point));
  323. Builder.SetCurrentDebugLocation(DbgLoc);
  324. }
  325. };
  326. // RAII object that stores the current fast math settings and restores
  327. // them when the object is destroyed.
  328. class FastMathFlagGuard {
  329. IRBuilderBase &Builder;
  330. FastMathFlags FMF;
  331. MDNode *FPMathTag;
  332. bool IsFPConstrained;
  333. fp::ExceptionBehavior DefaultConstrainedExcept;
  334. RoundingMode DefaultConstrainedRounding;
  335. public:
  336. FastMathFlagGuard(IRBuilderBase &B)
  337. : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag),
  338. IsFPConstrained(B.IsFPConstrained),
  339. DefaultConstrainedExcept(B.DefaultConstrainedExcept),
  340. DefaultConstrainedRounding(B.DefaultConstrainedRounding) {}
  341. FastMathFlagGuard(const FastMathFlagGuard &) = delete;
  342. FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
  343. ~FastMathFlagGuard() {
  344. Builder.FMF = FMF;
  345. Builder.DefaultFPMathTag = FPMathTag;
  346. Builder.IsFPConstrained = IsFPConstrained;
  347. Builder.DefaultConstrainedExcept = DefaultConstrainedExcept;
  348. Builder.DefaultConstrainedRounding = DefaultConstrainedRounding;
  349. }
  350. };
  351. // RAII object that stores the current default operand bundles and restores
  352. // them when the object is destroyed.
  353. class OperandBundlesGuard {
  354. IRBuilderBase &Builder;
  355. ArrayRef<OperandBundleDef> DefaultOperandBundles;
  356. public:
  357. OperandBundlesGuard(IRBuilderBase &B)
  358. : Builder(B), DefaultOperandBundles(B.DefaultOperandBundles) {}
  359. OperandBundlesGuard(const OperandBundlesGuard &) = delete;
  360. OperandBundlesGuard &operator=(const OperandBundlesGuard &) = delete;
  361. ~OperandBundlesGuard() {
  362. Builder.DefaultOperandBundles = DefaultOperandBundles;
  363. }
  364. };
  365. //===--------------------------------------------------------------------===//
  366. // Miscellaneous creation methods.
  367. //===--------------------------------------------------------------------===//
  368. /// Make a new global variable with initializer type i8*
  369. ///
  370. /// Make a new global variable with an initializer that has array of i8 type
  371. /// filled in with the null terminated string value specified. The new global
  372. /// variable will be marked mergable with any others of the same contents. If
  373. /// Name is specified, it is the name of the global variable created.
  374. ///
  375. /// If no module is given via \p M, it is take from the insertion point basic
  376. /// block.
  377. GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
  378. unsigned AddressSpace = 0,
  379. Module *M = nullptr);
  380. /// Get a constant value representing either true or false.
  381. ConstantInt *getInt1(bool V) {
  382. return ConstantInt::get(getInt1Ty(), V);
  383. }
  384. /// Get the constant value for i1 true.
  385. ConstantInt *getTrue() {
  386. return ConstantInt::getTrue(Context);
  387. }
  388. /// Get the constant value for i1 false.
  389. ConstantInt *getFalse() {
  390. return ConstantInt::getFalse(Context);
  391. }
  392. /// Get a constant 8-bit value.
  393. ConstantInt *getInt8(uint8_t C) {
  394. return ConstantInt::get(getInt8Ty(), C);
  395. }
  396. /// Get a constant 16-bit value.
  397. ConstantInt *getInt16(uint16_t C) {
  398. return ConstantInt::get(getInt16Ty(), C);
  399. }
  400. /// Get a constant 32-bit value.
  401. ConstantInt *getInt32(uint32_t C) {
  402. return ConstantInt::get(getInt32Ty(), C);
  403. }
  404. /// Get a constant 64-bit value.
  405. ConstantInt *getInt64(uint64_t C) {
  406. return ConstantInt::get(getInt64Ty(), C);
  407. }
  408. /// Get a constant N-bit value, zero extended or truncated from
  409. /// a 64-bit value.
  410. ConstantInt *getIntN(unsigned N, uint64_t C) {
  411. return ConstantInt::get(getIntNTy(N), C);
  412. }
  413. /// Get a constant integer value.
  414. ConstantInt *getInt(const APInt &AI) {
  415. return ConstantInt::get(Context, AI);
  416. }
  417. //===--------------------------------------------------------------------===//
  418. // Type creation methods
  419. //===--------------------------------------------------------------------===//
  420. /// Fetch the type representing a single bit
  421. IntegerType *getInt1Ty() {
  422. return Type::getInt1Ty(Context);
  423. }
  424. /// Fetch the type representing an 8-bit integer.
  425. IntegerType *getInt8Ty() {
  426. return Type::getInt8Ty(Context);
  427. }
  428. /// Fetch the type representing a 16-bit integer.
  429. IntegerType *getInt16Ty() {
  430. return Type::getInt16Ty(Context);
  431. }
  432. /// Fetch the type representing a 32-bit integer.
  433. IntegerType *getInt32Ty() {
  434. return Type::getInt32Ty(Context);
  435. }
  436. /// Fetch the type representing a 64-bit integer.
  437. IntegerType *getInt64Ty() {
  438. return Type::getInt64Ty(Context);
  439. }
  440. /// Fetch the type representing a 128-bit integer.
  441. IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
  442. /// Fetch the type representing an N-bit integer.
  443. IntegerType *getIntNTy(unsigned N) {
  444. return Type::getIntNTy(Context, N);
  445. }
  446. /// Fetch the type representing a 16-bit floating point value.
  447. Type *getHalfTy() {
  448. return Type::getHalfTy(Context);
  449. }
  450. /// Fetch the type representing a 16-bit brain floating point value.
  451. Type *getBFloatTy() {
  452. return Type::getBFloatTy(Context);
  453. }
  454. /// Fetch the type representing a 32-bit floating point value.
  455. Type *getFloatTy() {
  456. return Type::getFloatTy(Context);
  457. }
  458. /// Fetch the type representing a 64-bit floating point value.
  459. Type *getDoubleTy() {
  460. return Type::getDoubleTy(Context);
  461. }
  462. /// Fetch the type representing void.
  463. Type *getVoidTy() {
  464. return Type::getVoidTy(Context);
  465. }
  466. /// Fetch the type representing a pointer to an 8-bit integer value.
  467. PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
  468. return Type::getInt8PtrTy(Context, AddrSpace);
  469. }
  470. /// Fetch the type representing a pointer to an integer value.
  471. IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
  472. return DL.getIntPtrType(Context, AddrSpace);
  473. }
  474. //===--------------------------------------------------------------------===//
  475. // Intrinsic creation methods
  476. //===--------------------------------------------------------------------===//
  477. /// Create and insert a memset to the specified pointer and the
  478. /// specified value.
  479. ///
  480. /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
  481. /// specified, it will be added to the instruction. Likewise with alias.scope
  482. /// and noalias tags.
  483. CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size,
  484. MaybeAlign Align, bool isVolatile = false,
  485. MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
  486. MDNode *NoAliasTag = nullptr) {
  487. return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
  488. TBAATag, ScopeTag, NoAliasTag);
  489. }
  490. CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, MaybeAlign Align,
  491. bool isVolatile = false, MDNode *TBAATag = nullptr,
  492. MDNode *ScopeTag = nullptr,
  493. MDNode *NoAliasTag = nullptr);
  494. /// Create and insert an element unordered-atomic memset of the region of
  495. /// memory starting at the given pointer to the given value.
  496. ///
  497. /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
  498. /// specified, it will be added to the instruction. Likewise with alias.scope
  499. /// and noalias tags.
  500. CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
  501. uint64_t Size, Align Alignment,
  502. uint32_t ElementSize,
  503. MDNode *TBAATag = nullptr,
  504. MDNode *ScopeTag = nullptr,
  505. MDNode *NoAliasTag = nullptr) {
  506. return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
  507. Align(Alignment), ElementSize,
  508. TBAATag, ScopeTag, NoAliasTag);
  509. }
  510. CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
  511. Value *Size, Align Alignment,
  512. uint32_t ElementSize,
  513. MDNode *TBAATag = nullptr,
  514. MDNode *ScopeTag = nullptr,
  515. MDNode *NoAliasTag = nullptr);
  516. /// Create and insert a memcpy between the specified pointers.
  517. ///
  518. /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
  519. /// specified, it will be added to the instruction. Likewise with alias.scope
  520. /// and noalias tags.
  521. CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
  522. MaybeAlign SrcAlign, uint64_t Size,
  523. bool isVolatile = false, MDNode *TBAATag = nullptr,
  524. MDNode *TBAAStructTag = nullptr,
  525. MDNode *ScopeTag = nullptr,
  526. MDNode *NoAliasTag = nullptr) {
  527. return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
  528. isVolatile, TBAATag, TBAAStructTag, ScopeTag,
  529. NoAliasTag);
  530. }
  531. CallInst *CreateMemTransferInst(
  532. Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, Value *Src,
  533. MaybeAlign SrcAlign, Value *Size, bool isVolatile = false,
  534. MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
  535. MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr);
  536. CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
  537. MaybeAlign SrcAlign, Value *Size,
  538. bool isVolatile = false, MDNode *TBAATag = nullptr,
  539. MDNode *TBAAStructTag = nullptr,
  540. MDNode *ScopeTag = nullptr,
  541. MDNode *NoAliasTag = nullptr) {
  542. return CreateMemTransferInst(Intrinsic::memcpy, Dst, DstAlign, Src,
  543. SrcAlign, Size, isVolatile, TBAATag,
  544. TBAAStructTag, ScopeTag, NoAliasTag);
  545. }
  546. CallInst *
  547. CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign, Value *Src,
  548. MaybeAlign SrcAlign, Value *Size, bool IsVolatile = false,
  549. MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
  550. MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr);
  551. /// Create and insert an element unordered-atomic memcpy between the
  552. /// specified pointers.
  553. ///
  554. /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
  555. ///
  556. /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
  557. /// specified, it will be added to the instruction. Likewise with alias.scope
  558. /// and noalias tags.
  559. CallInst *CreateElementUnorderedAtomicMemCpy(
  560. Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
  561. uint32_t ElementSize, MDNode *TBAATag = nullptr,
  562. MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
  563. MDNode *NoAliasTag = nullptr);
  564. CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
  565. MaybeAlign SrcAlign, uint64_t Size,
  566. bool isVolatile = false, MDNode *TBAATag = nullptr,
  567. MDNode *ScopeTag = nullptr,
  568. MDNode *NoAliasTag = nullptr) {
  569. return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
  570. isVolatile, TBAATag, ScopeTag, NoAliasTag);
  571. }
  572. CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
  573. MaybeAlign SrcAlign, Value *Size,
  574. bool isVolatile = false, MDNode *TBAATag = nullptr,
  575. MDNode *ScopeTag = nullptr,
  576. MDNode *NoAliasTag = nullptr);
  577. /// \brief Create and insert an element unordered-atomic memmove between the
  578. /// specified pointers.
  579. ///
  580. /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
  581. /// respectively.
  582. ///
  583. /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
  584. /// specified, it will be added to the instruction. Likewise with alias.scope
  585. /// and noalias tags.
  586. CallInst *CreateElementUnorderedAtomicMemMove(
  587. Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
  588. uint32_t ElementSize, MDNode *TBAATag = nullptr,
  589. MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
  590. MDNode *NoAliasTag = nullptr);
  591. /// Create a sequential vector fadd reduction intrinsic of the source vector.
  592. /// The first parameter is a scalar accumulator value. An unordered reduction
  593. /// can be created by adding the reassoc fast-math flag to the resulting
  594. /// sequential reduction.
  595. CallInst *CreateFAddReduce(Value *Acc, Value *Src);
  596. /// Create a sequential vector fmul reduction intrinsic of the source vector.
  597. /// The first parameter is a scalar accumulator value. An unordered reduction
  598. /// can be created by adding the reassoc fast-math flag to the resulting
  599. /// sequential reduction.
  600. CallInst *CreateFMulReduce(Value *Acc, Value *Src);
  601. /// Create a vector int add reduction intrinsic of the source vector.
  602. CallInst *CreateAddReduce(Value *Src);
  603. /// Create a vector int mul reduction intrinsic of the source vector.
  604. CallInst *CreateMulReduce(Value *Src);
  605. /// Create a vector int AND reduction intrinsic of the source vector.
  606. CallInst *CreateAndReduce(Value *Src);
  607. /// Create a vector int OR reduction intrinsic of the source vector.
  608. CallInst *CreateOrReduce(Value *Src);
  609. /// Create a vector int XOR reduction intrinsic of the source vector.
  610. CallInst *CreateXorReduce(Value *Src);
  611. /// Create a vector integer max reduction intrinsic of the source
  612. /// vector.
  613. CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
  614. /// Create a vector integer min reduction intrinsic of the source
  615. /// vector.
  616. CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
  617. /// Create a vector float max reduction intrinsic of the source
  618. /// vector.
  619. CallInst *CreateFPMaxReduce(Value *Src);
  620. /// Create a vector float min reduction intrinsic of the source
  621. /// vector.
  622. CallInst *CreateFPMinReduce(Value *Src);
  623. /// Create a lifetime.start intrinsic.
  624. ///
  625. /// If the pointer isn't i8* it will be converted.
  626. CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
  627. /// Create a lifetime.end intrinsic.
  628. ///
  629. /// If the pointer isn't i8* it will be converted.
  630. CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
  631. /// Create a call to invariant.start intrinsic.
  632. ///
  633. /// If the pointer isn't i8* it will be converted.
  634. CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
  635. /// Create a call to Masked Load intrinsic
  636. CallInst *CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask,
  637. Value *PassThru = nullptr, const Twine &Name = "");
  638. /// Create a call to Masked Store intrinsic
  639. CallInst *CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment,
  640. Value *Mask);
  641. /// Create a call to Masked Gather intrinsic
  642. CallInst *CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment,
  643. Value *Mask = nullptr, Value *PassThru = nullptr,
  644. const Twine &Name = "");
  645. /// Create a call to Masked Scatter intrinsic
  646. CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment,
  647. Value *Mask = nullptr);
  648. /// Create an assume intrinsic call that allows the optimizer to
  649. /// assume that the provided condition will be true.
  650. ///
  651. /// The optional argument \p OpBundles specifies operand bundles that are
  652. /// added to the call instruction.
  653. CallInst *CreateAssumption(Value *Cond,
  654. ArrayRef<OperandBundleDef> OpBundles = llvm::None);
  655. /// Create a llvm.experimental.noalias.scope.decl intrinsic call.
  656. Instruction *CreateNoAliasScopeDeclaration(Value *Scope);
  657. Instruction *CreateNoAliasScopeDeclaration(MDNode *ScopeTag) {
  658. return CreateNoAliasScopeDeclaration(
  659. MetadataAsValue::get(Context, ScopeTag));
  660. }
  661. /// Create a call to the experimental.gc.statepoint intrinsic to
  662. /// start a new statepoint sequence.
  663. CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
  664. Value *ActualCallee,
  665. ArrayRef<Value *> CallArgs,
  666. Optional<ArrayRef<Value *>> DeoptArgs,
  667. ArrayRef<Value *> GCArgs,
  668. const Twine &Name = "");
  669. /// Create a call to the experimental.gc.statepoint intrinsic to
  670. /// start a new statepoint sequence.
  671. CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
  672. Value *ActualCallee, uint32_t Flags,
  673. ArrayRef<Value *> CallArgs,
  674. Optional<ArrayRef<Use>> TransitionArgs,
  675. Optional<ArrayRef<Use>> DeoptArgs,
  676. ArrayRef<Value *> GCArgs,
  677. const Twine &Name = "");
  678. /// Conveninence function for the common case when CallArgs are filled
  679. /// in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
  680. /// .get()'ed to get the Value pointer.
  681. CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
  682. Value *ActualCallee, ArrayRef<Use> CallArgs,
  683. Optional<ArrayRef<Value *>> DeoptArgs,
  684. ArrayRef<Value *> GCArgs,
  685. const Twine &Name = "");
  686. /// Create an invoke to the experimental.gc.statepoint intrinsic to
  687. /// start a new statepoint sequence.
  688. InvokeInst *
  689. CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
  690. Value *ActualInvokee, BasicBlock *NormalDest,
  691. BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
  692. Optional<ArrayRef<Value *>> DeoptArgs,
  693. ArrayRef<Value *> GCArgs, const Twine &Name = "");
  694. /// Create an invoke to the experimental.gc.statepoint intrinsic to
  695. /// start a new statepoint sequence.
  696. InvokeInst *CreateGCStatepointInvoke(
  697. uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
  698. BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
  699. ArrayRef<Value *> InvokeArgs, Optional<ArrayRef<Use>> TransitionArgs,
  700. Optional<ArrayRef<Use>> DeoptArgs, ArrayRef<Value *> GCArgs,
  701. const Twine &Name = "");
  702. // Convenience function for the common case when CallArgs are filled in using
  703. // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
  704. // get the Value *.
  705. InvokeInst *
  706. CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
  707. Value *ActualInvokee, BasicBlock *NormalDest,
  708. BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
  709. Optional<ArrayRef<Value *>> DeoptArgs,
  710. ArrayRef<Value *> GCArgs, const Twine &Name = "");
  711. /// Create a call to the experimental.gc.result intrinsic to extract
  712. /// the result from a call wrapped in a statepoint.
  713. CallInst *CreateGCResult(Instruction *Statepoint,
  714. Type *ResultType,
  715. const Twine &Name = "");
  716. /// Create a call to the experimental.gc.relocate intrinsics to
  717. /// project the relocated value of one pointer from the statepoint.
  718. CallInst *CreateGCRelocate(Instruction *Statepoint,
  719. int BaseOffset,
  720. int DerivedOffset,
  721. Type *ResultType,
  722. const Twine &Name = "");
  723. /// Create a call to the experimental.gc.pointer.base intrinsic to get the
  724. /// base pointer for the specified derived pointer.
  725. CallInst *CreateGCGetPointerBase(Value *DerivedPtr, const Twine &Name = "");
  726. /// Create a call to the experimental.gc.get.pointer.offset intrinsic to get
  727. /// the offset of the specified derived pointer from its base.
  728. CallInst *CreateGCGetPointerOffset(Value *DerivedPtr, const Twine &Name = "");
  729. /// Create a call to llvm.vscale, multiplied by \p Scaling. The type of VScale
  730. /// will be the same type as that of \p Scaling.
  731. Value *CreateVScale(Constant *Scaling, const Twine &Name = "");
  732. /// Creates a vector of type \p DstType with the linear sequence <0, 1, ...>
  733. Value *CreateStepVector(Type *DstType, const Twine &Name = "");
  734. /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
  735. /// type.
  736. CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
  737. Instruction *FMFSource = nullptr,
  738. const Twine &Name = "");
  739. /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
  740. /// first type.
  741. CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
  742. Instruction *FMFSource = nullptr,
  743. const Twine &Name = "");
  744. /// Create a call to intrinsic \p ID with \p args, mangled using \p Types. If
  745. /// \p FMFSource is provided, copy fast-math-flags from that instruction to
  746. /// the intrinsic.
  747. CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
  748. ArrayRef<Value *> Args,
  749. Instruction *FMFSource = nullptr,
  750. const Twine &Name = "");
  751. /// Create call to the minnum intrinsic.
  752. CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
  753. return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
  754. }
  755. /// Create call to the maxnum intrinsic.
  756. CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
  757. return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
  758. }
  759. /// Create call to the minimum intrinsic.
  760. CallInst *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") {
  761. return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name);
  762. }
  763. /// Create call to the maximum intrinsic.
  764. CallInst *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") {
  765. return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name);
  766. }
  767. /// Create a call to the arithmetic_fence intrinsic.
  768. CallInst *CreateArithmeticFence(Value *Val, Type *DstType,
  769. const Twine &Name = "") {
  770. return CreateIntrinsic(Intrinsic::arithmetic_fence, DstType, Val, nullptr,
  771. Name);
  772. }
  773. /// Create a call to the experimental.vector.extract intrinsic.
  774. CallInst *CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx,
  775. const Twine &Name = "") {
  776. return CreateIntrinsic(Intrinsic::experimental_vector_extract,
  777. {DstType, SrcVec->getType()}, {SrcVec, Idx}, nullptr,
  778. Name);
  779. }
  780. /// Create a call to the experimental.vector.insert intrinsic.
  781. CallInst *CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec,
  782. Value *Idx, const Twine &Name = "") {
  783. return CreateIntrinsic(Intrinsic::experimental_vector_insert,
  784. {DstType, SubVec->getType()}, {SrcVec, SubVec, Idx},
  785. nullptr, Name);
  786. }
  787. private:
  788. /// Create a call to a masked intrinsic with given Id.
  789. CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
  790. ArrayRef<Type *> OverloadedTypes,
  791. const Twine &Name = "");
  792. Value *getCastedInt8PtrValue(Value *Ptr);
  793. //===--------------------------------------------------------------------===//
  794. // Instruction creation methods: Terminators
  795. //===--------------------------------------------------------------------===//
  796. private:
  797. /// Helper to add branch weight and unpredictable metadata onto an
  798. /// instruction.
  799. /// \returns The annotated instruction.
  800. template <typename InstTy>
  801. InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
  802. if (Weights)
  803. I->setMetadata(LLVMContext::MD_prof, Weights);
  804. if (Unpredictable)
  805. I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
  806. return I;
  807. }
  808. public:
  809. /// Create a 'ret void' instruction.
  810. ReturnInst *CreateRetVoid() {
  811. return Insert(ReturnInst::Create(Context));
  812. }
  813. /// Create a 'ret <val>' instruction.
  814. ReturnInst *CreateRet(Value *V) {
  815. return Insert(ReturnInst::Create(Context, V));
  816. }
  817. /// Create a sequence of N insertvalue instructions,
  818. /// with one Value from the retVals array each, that build a aggregate
  819. /// return value one value at a time, and a ret instruction to return
  820. /// the resulting aggregate value.
  821. ///
  822. /// This is a convenience function for code that uses aggregate return values
  823. /// as a vehicle for having multiple return values.
  824. ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
  825. Value *V = UndefValue::get(getCurrentFunctionReturnType());
  826. for (unsigned i = 0; i != N; ++i)
  827. V = CreateInsertValue(V, retVals[i], i, "mrv");
  828. return Insert(ReturnInst::Create(Context, V));
  829. }
  830. /// Create an unconditional 'br label X' instruction.
  831. BranchInst *CreateBr(BasicBlock *Dest) {
  832. return Insert(BranchInst::Create(Dest));
  833. }
  834. /// Create a conditional 'br Cond, TrueDest, FalseDest'
  835. /// instruction.
  836. BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
  837. MDNode *BranchWeights = nullptr,
  838. MDNode *Unpredictable = nullptr) {
  839. return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
  840. BranchWeights, Unpredictable));
  841. }
  842. /// Create a conditional 'br Cond, TrueDest, FalseDest'
  843. /// instruction. Copy branch meta data if available.
  844. BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
  845. Instruction *MDSrc) {
  846. BranchInst *Br = BranchInst::Create(True, False, Cond);
  847. if (MDSrc) {
  848. unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
  849. LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
  850. Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
  851. }
  852. return Insert(Br);
  853. }
  854. /// Create a switch instruction with the specified value, default dest,
  855. /// and with a hint for the number of cases that will be added (for efficient
  856. /// allocation).
  857. SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
  858. MDNode *BranchWeights = nullptr,
  859. MDNode *Unpredictable = nullptr) {
  860. return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
  861. BranchWeights, Unpredictable));
  862. }
  863. /// Create an indirect branch instruction with the specified address
  864. /// operand, with an optional hint for the number of destinations that will be
  865. /// added (for efficient allocation).
  866. IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
  867. return Insert(IndirectBrInst::Create(Addr, NumDests));
  868. }
  869. /// Create an invoke instruction.
  870. InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
  871. BasicBlock *NormalDest, BasicBlock *UnwindDest,
  872. ArrayRef<Value *> Args,
  873. ArrayRef<OperandBundleDef> OpBundles,
  874. const Twine &Name = "") {
  875. InvokeInst *II =
  876. InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, OpBundles);
  877. if (IsFPConstrained)
  878. setConstrainedFPCallAttr(II);
  879. return Insert(II, Name);
  880. }
  881. InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
  882. BasicBlock *NormalDest, BasicBlock *UnwindDest,
  883. ArrayRef<Value *> Args = None,
  884. const Twine &Name = "") {
  885. InvokeInst *II =
  886. InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args);
  887. if (IsFPConstrained)
  888. setConstrainedFPCallAttr(II);
  889. return Insert(II, Name);
  890. }
  891. InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
  892. BasicBlock *UnwindDest, ArrayRef<Value *> Args,
  893. ArrayRef<OperandBundleDef> OpBundles,
  894. const Twine &Name = "") {
  895. return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
  896. NormalDest, UnwindDest, Args, OpBundles, Name);
  897. }
  898. InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
  899. BasicBlock *UnwindDest,
  900. ArrayRef<Value *> Args = None,
  901. const Twine &Name = "") {
  902. return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
  903. NormalDest, UnwindDest, Args, Name);
  904. }
  905. /// \brief Create a callbr instruction.
  906. CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
  907. BasicBlock *DefaultDest,
  908. ArrayRef<BasicBlock *> IndirectDests,
  909. ArrayRef<Value *> Args = None,
  910. const Twine &Name = "") {
  911. return Insert(CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests,
  912. Args), Name);
  913. }
  914. CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
  915. BasicBlock *DefaultDest,
  916. ArrayRef<BasicBlock *> IndirectDests,
  917. ArrayRef<Value *> Args,
  918. ArrayRef<OperandBundleDef> OpBundles,
  919. const Twine &Name = "") {
  920. return Insert(
  921. CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
  922. OpBundles), Name);
  923. }
  924. CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
  925. ArrayRef<BasicBlock *> IndirectDests,
  926. ArrayRef<Value *> Args = None,
  927. const Twine &Name = "") {
  928. return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
  929. DefaultDest, IndirectDests, Args, Name);
  930. }
  931. CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
  932. ArrayRef<BasicBlock *> IndirectDests,
  933. ArrayRef<Value *> Args,
  934. ArrayRef<OperandBundleDef> OpBundles,
  935. const Twine &Name = "") {
  936. return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
  937. DefaultDest, IndirectDests, Args, Name);
  938. }
  939. ResumeInst *CreateResume(Value *Exn) {
  940. return Insert(ResumeInst::Create(Exn));
  941. }
  942. CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
  943. BasicBlock *UnwindBB = nullptr) {
  944. return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
  945. }
  946. CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
  947. unsigned NumHandlers,
  948. const Twine &Name = "") {
  949. return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
  950. Name);
  951. }
  952. CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
  953. const Twine &Name = "") {
  954. return Insert(CatchPadInst::Create(ParentPad, Args), Name);
  955. }
  956. CleanupPadInst *CreateCleanupPad(Value *ParentPad,
  957. ArrayRef<Value *> Args = None,
  958. const Twine &Name = "") {
  959. return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
  960. }
  961. CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
  962. return Insert(CatchReturnInst::Create(CatchPad, BB));
  963. }
  964. UnreachableInst *CreateUnreachable() {
  965. return Insert(new UnreachableInst(Context));
  966. }
  967. //===--------------------------------------------------------------------===//
  968. // Instruction creation methods: Binary Operators
  969. //===--------------------------------------------------------------------===//
  970. private:
  971. BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
  972. Value *LHS, Value *RHS,
  973. const Twine &Name,
  974. bool HasNUW, bool HasNSW) {
  975. BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
  976. if (HasNUW) BO->setHasNoUnsignedWrap();
  977. if (HasNSW) BO->setHasNoSignedWrap();
  978. return BO;
  979. }
  980. Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
  981. FastMathFlags FMF) const {
  982. if (!FPMD)
  983. FPMD = DefaultFPMathTag;
  984. if (FPMD)
  985. I->setMetadata(LLVMContext::MD_fpmath, FPMD);
  986. I->setFastMathFlags(FMF);
  987. return I;
  988. }
  989. Value *foldConstant(Instruction::BinaryOps Opc, Value *L,
  990. Value *R, const Twine &Name) const {
  991. auto *LC = dyn_cast<Constant>(L);
  992. auto *RC = dyn_cast<Constant>(R);
  993. return (LC && RC) ? Insert(Folder.CreateBinOp(Opc, LC, RC), Name) : nullptr;
  994. }
  995. Value *getConstrainedFPRounding(Optional<RoundingMode> Rounding) {
  996. RoundingMode UseRounding = DefaultConstrainedRounding;
  997. if (Rounding.hasValue())
  998. UseRounding = Rounding.getValue();
  999. Optional<StringRef> RoundingStr = convertRoundingModeToStr(UseRounding);
  1000. assert(RoundingStr.hasValue() && "Garbage strict rounding mode!");
  1001. auto *RoundingMDS = MDString::get(Context, RoundingStr.getValue());
  1002. return MetadataAsValue::get(Context, RoundingMDS);
  1003. }
  1004. Value *getConstrainedFPExcept(Optional<fp::ExceptionBehavior> Except) {
  1005. fp::ExceptionBehavior UseExcept = DefaultConstrainedExcept;
  1006. if (Except.hasValue())
  1007. UseExcept = Except.getValue();
  1008. Optional<StringRef> ExceptStr = convertExceptionBehaviorToStr(UseExcept);
  1009. assert(ExceptStr.hasValue() && "Garbage strict exception behavior!");
  1010. auto *ExceptMDS = MDString::get(Context, ExceptStr.getValue());
  1011. return MetadataAsValue::get(Context, ExceptMDS);
  1012. }
  1013. Value *getConstrainedFPPredicate(CmpInst::Predicate Predicate) {
  1014. assert(CmpInst::isFPPredicate(Predicate) &&
  1015. Predicate != CmpInst::FCMP_FALSE &&
  1016. Predicate != CmpInst::FCMP_TRUE &&
  1017. "Invalid constrained FP comparison predicate!");
  1018. StringRef PredicateStr = CmpInst::getPredicateName(Predicate);
  1019. auto *PredicateMDS = MDString::get(Context, PredicateStr);
  1020. return MetadataAsValue::get(Context, PredicateMDS);
  1021. }
  1022. public:
  1023. Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
  1024. bool HasNUW = false, bool HasNSW = false) {
  1025. if (auto *V = Folder.FoldAdd(LHS, RHS, HasNUW, HasNSW))
  1026. return V;
  1027. return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
  1028. HasNUW, HasNSW);
  1029. }
  1030. Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
  1031. return CreateAdd(LHS, RHS, Name, false, true);
  1032. }
  1033. Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
  1034. return CreateAdd(LHS, RHS, Name, true, false);
  1035. }
  1036. Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
  1037. bool HasNUW = false, bool HasNSW = false) {
  1038. if (auto *LC = dyn_cast<Constant>(LHS))
  1039. if (auto *RC = dyn_cast<Constant>(RHS))
  1040. return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
  1041. return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
  1042. HasNUW, HasNSW);
  1043. }
  1044. Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
  1045. return CreateSub(LHS, RHS, Name, false, true);
  1046. }
  1047. Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
  1048. return CreateSub(LHS, RHS, Name, true, false);
  1049. }
  1050. Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
  1051. bool HasNUW = false, bool HasNSW = false) {
  1052. if (auto *LC = dyn_cast<Constant>(LHS))
  1053. if (auto *RC = dyn_cast<Constant>(RHS))
  1054. return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
  1055. return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
  1056. HasNUW, HasNSW);
  1057. }
  1058. Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
  1059. return CreateMul(LHS, RHS, Name, false, true);
  1060. }
  1061. Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
  1062. return CreateMul(LHS, RHS, Name, true, false);
  1063. }
  1064. Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
  1065. bool isExact = false) {
  1066. if (auto *LC = dyn_cast<Constant>(LHS))
  1067. if (auto *RC = dyn_cast<Constant>(RHS))
  1068. return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
  1069. if (!isExact)
  1070. return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
  1071. return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
  1072. }
  1073. Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
  1074. return CreateUDiv(LHS, RHS, Name, true);
  1075. }
  1076. Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
  1077. bool isExact = false) {
  1078. if (auto *LC = dyn_cast<Constant>(LHS))
  1079. if (auto *RC = dyn_cast<Constant>(RHS))
  1080. return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
  1081. if (!isExact)
  1082. return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
  1083. return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
  1084. }
  1085. Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
  1086. return CreateSDiv(LHS, RHS, Name, true);
  1087. }
  1088. Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
  1089. if (Value *V = foldConstant(Instruction::URem, LHS, RHS, Name)) return V;
  1090. return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
  1091. }
  1092. Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
  1093. if (Value *V = foldConstant(Instruction::SRem, LHS, RHS, Name)) return V;
  1094. return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
  1095. }
  1096. Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
  1097. bool HasNUW = false, bool HasNSW = false) {
  1098. if (auto *LC = dyn_cast<Constant>(LHS))
  1099. if (auto *RC = dyn_cast<Constant>(RHS))
  1100. return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
  1101. return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
  1102. HasNUW, HasNSW);
  1103. }
  1104. Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
  1105. bool HasNUW = false, bool HasNSW = false) {
  1106. return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
  1107. HasNUW, HasNSW);
  1108. }
  1109. Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
  1110. bool HasNUW = false, bool HasNSW = false) {
  1111. return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
  1112. HasNUW, HasNSW);
  1113. }
  1114. Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
  1115. bool isExact = false) {
  1116. if (auto *LC = dyn_cast<Constant>(LHS))
  1117. if (auto *RC = dyn_cast<Constant>(RHS))
  1118. return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
  1119. if (!isExact)
  1120. return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
  1121. return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
  1122. }
  1123. Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
  1124. bool isExact = false) {
  1125. return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1126. }
  1127. Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
  1128. bool isExact = false) {
  1129. return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1130. }
  1131. Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
  1132. bool isExact = false) {
  1133. if (auto *LC = dyn_cast<Constant>(LHS))
  1134. if (auto *RC = dyn_cast<Constant>(RHS))
  1135. return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
  1136. if (!isExact)
  1137. return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
  1138. return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
  1139. }
  1140. Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
  1141. bool isExact = false) {
  1142. return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1143. }
  1144. Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
  1145. bool isExact = false) {
  1146. return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
  1147. }
  1148. Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
  1149. if (auto *V = Folder.FoldAnd(LHS, RHS))
  1150. return V;
  1151. return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
  1152. }
  1153. Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
  1154. return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1155. }
  1156. Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
  1157. return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1158. }
  1159. Value *CreateAnd(ArrayRef<Value*> Ops) {
  1160. assert(!Ops.empty());
  1161. Value *Accum = Ops[0];
  1162. for (unsigned i = 1; i < Ops.size(); i++)
  1163. Accum = CreateAnd(Accum, Ops[i]);
  1164. return Accum;
  1165. }
  1166. Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
  1167. if (auto *V = Folder.FoldOr(LHS, RHS))
  1168. return V;
  1169. return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
  1170. }
  1171. Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
  1172. return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1173. }
  1174. Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
  1175. return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1176. }
  1177. Value *CreateOr(ArrayRef<Value*> Ops) {
  1178. assert(!Ops.empty());
  1179. Value *Accum = Ops[0];
  1180. for (unsigned i = 1; i < Ops.size(); i++)
  1181. Accum = CreateOr(Accum, Ops[i]);
  1182. return Accum;
  1183. }
  1184. Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
  1185. if (Value *V = foldConstant(Instruction::Xor, LHS, RHS, Name)) return V;
  1186. return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
  1187. }
  1188. Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
  1189. return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1190. }
  1191. Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
  1192. return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
  1193. }
  1194. Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "",
  1195. MDNode *FPMD = nullptr) {
  1196. if (IsFPConstrained)
  1197. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
  1198. L, R, nullptr, Name, FPMD);
  1199. if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
  1200. Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMF);
  1201. return Insert(I, Name);
  1202. }
  1203. /// Copy fast-math-flags from an instruction rather than using the builder's
  1204. /// default FMF.
  1205. Value *CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource,
  1206. const Twine &Name = "") {
  1207. if (IsFPConstrained)
  1208. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
  1209. L, R, FMFSource, Name);
  1210. if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
  1211. Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), nullptr,
  1212. FMFSource->getFastMathFlags());
  1213. return Insert(I, Name);
  1214. }
  1215. Value *CreateFSub(Value *L, Value *R, const Twine &Name = "",
  1216. MDNode *FPMD = nullptr) {
  1217. if (IsFPConstrained)
  1218. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
  1219. L, R, nullptr, Name, FPMD);
  1220. if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
  1221. Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMF);
  1222. return Insert(I, Name);
  1223. }
  1224. /// Copy fast-math-flags from an instruction rather than using the builder's
  1225. /// default FMF.
  1226. Value *CreateFSubFMF(Value *L, Value *R, Instruction *FMFSource,
  1227. const Twine &Name = "") {
  1228. if (IsFPConstrained)
  1229. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
  1230. L, R, FMFSource, Name);
  1231. if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
  1232. Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), nullptr,
  1233. FMFSource->getFastMathFlags());
  1234. return Insert(I, Name);
  1235. }
  1236. Value *CreateFMul(Value *L, Value *R, const Twine &Name = "",
  1237. MDNode *FPMD = nullptr) {
  1238. if (IsFPConstrained)
  1239. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
  1240. L, R, nullptr, Name, FPMD);
  1241. if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
  1242. Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMF);
  1243. return Insert(I, Name);
  1244. }
  1245. /// Copy fast-math-flags from an instruction rather than using the builder's
  1246. /// default FMF.
  1247. Value *CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource,
  1248. const Twine &Name = "") {
  1249. if (IsFPConstrained)
  1250. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
  1251. L, R, FMFSource, Name);
  1252. if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
  1253. Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), nullptr,
  1254. FMFSource->getFastMathFlags());
  1255. return Insert(I, Name);
  1256. }
  1257. Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "",
  1258. MDNode *FPMD = nullptr) {
  1259. if (IsFPConstrained)
  1260. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
  1261. L, R, nullptr, Name, FPMD);
  1262. if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
  1263. Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMF);
  1264. return Insert(I, Name);
  1265. }
  1266. /// Copy fast-math-flags from an instruction rather than using the builder's
  1267. /// default FMF.
  1268. Value *CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource,
  1269. const Twine &Name = "") {
  1270. if (IsFPConstrained)
  1271. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
  1272. L, R, FMFSource, Name);
  1273. if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
  1274. Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), nullptr,
  1275. FMFSource->getFastMathFlags());
  1276. return Insert(I, Name);
  1277. }
  1278. Value *CreateFRem(Value *L, Value *R, const Twine &Name = "",
  1279. MDNode *FPMD = nullptr) {
  1280. if (IsFPConstrained)
  1281. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
  1282. L, R, nullptr, Name, FPMD);
  1283. if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
  1284. Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMF);
  1285. return Insert(I, Name);
  1286. }
  1287. /// Copy fast-math-flags from an instruction rather than using the builder's
  1288. /// default FMF.
  1289. Value *CreateFRemFMF(Value *L, Value *R, Instruction *FMFSource,
  1290. const Twine &Name = "") {
  1291. if (IsFPConstrained)
  1292. return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
  1293. L, R, FMFSource, Name);
  1294. if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
  1295. Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), nullptr,
  1296. FMFSource->getFastMathFlags());
  1297. return Insert(I, Name);
  1298. }
  1299. Value *CreateBinOp(Instruction::BinaryOps Opc,
  1300. Value *LHS, Value *RHS, const Twine &Name = "",
  1301. MDNode *FPMathTag = nullptr) {
  1302. if (Value *V = foldConstant(Opc, LHS, RHS, Name)) return V;
  1303. Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
  1304. if (isa<FPMathOperator>(BinOp))
  1305. setFPAttrs(BinOp, FPMathTag, FMF);
  1306. return Insert(BinOp, Name);
  1307. }
  1308. Value *CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name = "") {
  1309. assert(Cond2->getType()->isIntOrIntVectorTy(1));
  1310. return CreateSelect(Cond1, Cond2,
  1311. ConstantInt::getNullValue(Cond2->getType()), Name);
  1312. }
  1313. Value *CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name = "") {
  1314. assert(Cond2->getType()->isIntOrIntVectorTy(1));
  1315. return CreateSelect(Cond1, ConstantInt::getAllOnesValue(Cond2->getType()),
  1316. Cond2, Name);
  1317. }
  1318. // NOTE: this is sequential, non-commutative, ordered reduction!
  1319. Value *CreateLogicalOr(ArrayRef<Value *> Ops) {
  1320. assert(!Ops.empty());
  1321. Value *Accum = Ops[0];
  1322. for (unsigned i = 1; i < Ops.size(); i++)
  1323. Accum = CreateLogicalOr(Accum, Ops[i]);
  1324. return Accum;
  1325. }
  1326. CallInst *CreateConstrainedFPBinOp(
  1327. Intrinsic::ID ID, Value *L, Value *R, Instruction *FMFSource = nullptr,
  1328. const Twine &Name = "", MDNode *FPMathTag = nullptr,
  1329. Optional<RoundingMode> Rounding = None,
  1330. Optional<fp::ExceptionBehavior> Except = None);
  1331. Value *CreateNeg(Value *V, const Twine &Name = "",
  1332. bool HasNUW = false, bool HasNSW = false) {
  1333. if (auto *VC = dyn_cast<Constant>(V))
  1334. return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
  1335. BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
  1336. if (HasNUW) BO->setHasNoUnsignedWrap();
  1337. if (HasNSW) BO->setHasNoSignedWrap();
  1338. return BO;
  1339. }
  1340. Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
  1341. return CreateNeg(V, Name, false, true);
  1342. }
  1343. Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
  1344. return CreateNeg(V, Name, true, false);
  1345. }
  1346. Value *CreateFNeg(Value *V, const Twine &Name = "",
  1347. MDNode *FPMathTag = nullptr) {
  1348. if (auto *VC = dyn_cast<Constant>(V))
  1349. return Insert(Folder.CreateFNeg(VC), Name);
  1350. return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), FPMathTag, FMF),
  1351. Name);
  1352. }
  1353. /// Copy fast-math-flags from an instruction rather than using the builder's
  1354. /// default FMF.
  1355. Value *CreateFNegFMF(Value *V, Instruction *FMFSource,
  1356. const Twine &Name = "") {
  1357. if (auto *VC = dyn_cast<Constant>(V))
  1358. return Insert(Folder.CreateFNeg(VC), Name);
  1359. return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), nullptr,
  1360. FMFSource->getFastMathFlags()),
  1361. Name);
  1362. }
  1363. Value *CreateNot(Value *V, const Twine &Name = "") {
  1364. if (auto *VC = dyn_cast<Constant>(V))
  1365. return Insert(Folder.CreateNot(VC), Name);
  1366. return Insert(BinaryOperator::CreateNot(V), Name);
  1367. }
  1368. Value *CreateUnOp(Instruction::UnaryOps Opc,
  1369. Value *V, const Twine &Name = "",
  1370. MDNode *FPMathTag = nullptr) {
  1371. if (auto *VC = dyn_cast<Constant>(V))
  1372. return Insert(Folder.CreateUnOp(Opc, VC), Name);
  1373. Instruction *UnOp = UnaryOperator::Create(Opc, V);
  1374. if (isa<FPMathOperator>(UnOp))
  1375. setFPAttrs(UnOp, FPMathTag, FMF);
  1376. return Insert(UnOp, Name);
  1377. }
  1378. /// Create either a UnaryOperator or BinaryOperator depending on \p Opc.
  1379. /// Correct number of operands must be passed accordingly.
  1380. Value *CreateNAryOp(unsigned Opc, ArrayRef<Value *> Ops,
  1381. const Twine &Name = "", MDNode *FPMathTag = nullptr);
  1382. //===--------------------------------------------------------------------===//
  1383. // Instruction creation methods: Memory Instructions
  1384. //===--------------------------------------------------------------------===//
  1385. AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
  1386. Value *ArraySize = nullptr, const Twine &Name = "") {
  1387. const DataLayout &DL = BB->getModule()->getDataLayout();
  1388. Align AllocaAlign = DL.getPrefTypeAlign(Ty);
  1389. return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
  1390. }
  1391. AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
  1392. const Twine &Name = "") {
  1393. const DataLayout &DL = BB->getModule()->getDataLayout();
  1394. Align AllocaAlign = DL.getPrefTypeAlign(Ty);
  1395. unsigned AddrSpace = DL.getAllocaAddrSpace();
  1396. return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
  1397. }
  1398. /// Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of
  1399. /// converting the string to 'bool' for the isVolatile parameter.
  1400. LoadInst *CreateLoad(Type *Ty, Value *Ptr, const char *Name) {
  1401. return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
  1402. }
  1403. LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
  1404. return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
  1405. }
  1406. LoadInst *CreateLoad(Type *Ty, Value *Ptr, bool isVolatile,
  1407. const Twine &Name = "") {
  1408. return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), isVolatile, Name);
  1409. }
  1410. StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
  1411. return CreateAlignedStore(Val, Ptr, MaybeAlign(), isVolatile);
  1412. }
  1413. LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
  1414. const char *Name) {
  1415. return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
  1416. }
  1417. LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
  1418. const Twine &Name = "") {
  1419. return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
  1420. }
  1421. LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
  1422. bool isVolatile, const Twine &Name = "") {
  1423. if (!Align) {
  1424. const DataLayout &DL = BB->getModule()->getDataLayout();
  1425. Align = DL.getABITypeAlign(Ty);
  1426. }
  1427. return Insert(new LoadInst(Ty, Ptr, Twine(), isVolatile, *Align), Name);
  1428. }
  1429. StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align,
  1430. bool isVolatile = false) {
  1431. if (!Align) {
  1432. const DataLayout &DL = BB->getModule()->getDataLayout();
  1433. Align = DL.getABITypeAlign(Val->getType());
  1434. }
  1435. return Insert(new StoreInst(Val, Ptr, isVolatile, *Align));
  1436. }
  1437. FenceInst *CreateFence(AtomicOrdering Ordering,
  1438. SyncScope::ID SSID = SyncScope::System,
  1439. const Twine &Name = "") {
  1440. return Insert(new FenceInst(Context, Ordering, SSID), Name);
  1441. }
  1442. AtomicCmpXchgInst *
  1443. CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align,
  1444. AtomicOrdering SuccessOrdering,
  1445. AtomicOrdering FailureOrdering,
  1446. SyncScope::ID SSID = SyncScope::System) {
  1447. if (!Align) {
  1448. const DataLayout &DL = BB->getModule()->getDataLayout();
  1449. Align = llvm::Align(DL.getTypeStoreSize(New->getType()));
  1450. }
  1451. return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, *Align, SuccessOrdering,
  1452. FailureOrdering, SSID));
  1453. }
  1454. AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr,
  1455. Value *Val, MaybeAlign Align,
  1456. AtomicOrdering Ordering,
  1457. SyncScope::ID SSID = SyncScope::System) {
  1458. if (!Align) {
  1459. const DataLayout &DL = BB->getModule()->getDataLayout();
  1460. Align = llvm::Align(DL.getTypeStoreSize(Val->getType()));
  1461. }
  1462. return Insert(new AtomicRMWInst(Op, Ptr, Val, *Align, Ordering, SSID));
  1463. }
  1464. Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
  1465. const Twine &Name = "") {
  1466. if (auto *V = Folder.FoldGEP(Ty, Ptr, IdxList, /*IsInBounds=*/false))
  1467. return V;
  1468. return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
  1469. }
  1470. Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
  1471. const Twine &Name = "") {
  1472. if (auto *V = Folder.FoldGEP(Ty, Ptr, IdxList, /*IsInBounds=*/true))
  1473. return V;
  1474. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
  1475. }
  1476. Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
  1477. if (auto *V = Folder.FoldGEP(Ty, Ptr, {Idx}, /*IsInBounds=*/false))
  1478. return V;
  1479. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
  1480. }
  1481. Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
  1482. const Twine &Name = "") {
  1483. if (auto *V = Folder.FoldGEP(Ty, Ptr, {Idx}, /*IsInBounds=*/true))
  1484. return V;
  1485. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
  1486. }
  1487. Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
  1488. const Twine &Name = "") {
  1489. Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
  1490. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/false))
  1491. return V;
  1492. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
  1493. }
  1494. Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
  1495. const Twine &Name = "") {
  1496. Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
  1497. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/true))
  1498. return V;
  1499. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
  1500. }
  1501. Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
  1502. const Twine &Name = "") {
  1503. Value *Idxs[] = {
  1504. ConstantInt::get(Type::getInt32Ty(Context), Idx0),
  1505. ConstantInt::get(Type::getInt32Ty(Context), Idx1)
  1506. };
  1507. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/false))
  1508. return V;
  1509. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
  1510. }
  1511. Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
  1512. unsigned Idx1, const Twine &Name = "") {
  1513. Value *Idxs[] = {
  1514. ConstantInt::get(Type::getInt32Ty(Context), Idx0),
  1515. ConstantInt::get(Type::getInt32Ty(Context), Idx1)
  1516. };
  1517. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/true))
  1518. return V;
  1519. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
  1520. }
  1521. Value *CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
  1522. const Twine &Name = "") {
  1523. Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
  1524. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/false))
  1525. return V;
  1526. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
  1527. }
  1528. Value *CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
  1529. const Twine &Name = "") {
  1530. Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
  1531. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, /*IsInBounds=*/true))
  1532. return V;
  1533. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
  1534. }
  1535. Value *CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1,
  1536. const Twine &Name = "") {
  1537. Value *Idxs[] = {
  1538. ConstantInt::get(Type::getInt64Ty(Context), Idx0),
  1539. ConstantInt::get(Type::getInt64Ty(Context), Idx1)
  1540. };
  1541. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/false))
  1542. return V;
  1543. return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
  1544. }
  1545. Value *CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0,
  1546. uint64_t Idx1, const Twine &Name = "") {
  1547. Value *Idxs[] = {
  1548. ConstantInt::get(Type::getInt64Ty(Context), Idx0),
  1549. ConstantInt::get(Type::getInt64Ty(Context), Idx1)
  1550. };
  1551. if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, /*IsInBounds=*/true))
  1552. return V;
  1553. return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
  1554. }
  1555. Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
  1556. const Twine &Name = "") {
  1557. return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
  1558. }
  1559. /// Same as CreateGlobalString, but return a pointer with "i8*" type
  1560. /// instead of a pointer to array of i8.
  1561. ///
  1562. /// If no module is given via \p M, it is take from the insertion point basic
  1563. /// block.
  1564. Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
  1565. unsigned AddressSpace = 0,
  1566. Module *M = nullptr) {
  1567. GlobalVariable *GV = CreateGlobalString(Str, Name, AddressSpace, M);
  1568. Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
  1569. Constant *Indices[] = {Zero, Zero};
  1570. return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV,
  1571. Indices);
  1572. }
  1573. //===--------------------------------------------------------------------===//
  1574. // Instruction creation methods: Cast/Conversion Operators
  1575. //===--------------------------------------------------------------------===//
  1576. Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
  1577. return CreateCast(Instruction::Trunc, V, DestTy, Name);
  1578. }
  1579. Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
  1580. return CreateCast(Instruction::ZExt, V, DestTy, Name);
  1581. }
  1582. Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
  1583. return CreateCast(Instruction::SExt, V, DestTy, Name);
  1584. }
  1585. /// Create a ZExt or Trunc from the integer value V to DestTy. Return
  1586. /// the value untouched if the type of V is already DestTy.
  1587. Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
  1588. const Twine &Name = "") {
  1589. assert(V->getType()->isIntOrIntVectorTy() &&
  1590. DestTy->isIntOrIntVectorTy() &&
  1591. "Can only zero extend/truncate integers!");
  1592. Type *VTy = V->getType();
  1593. if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
  1594. return CreateZExt(V, DestTy, Name);
  1595. if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
  1596. return CreateTrunc(V, DestTy, Name);
  1597. return V;
  1598. }
  1599. /// Create a SExt or Trunc from the integer value V to DestTy. Return
  1600. /// the value untouched if the type of V is already DestTy.
  1601. Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
  1602. const Twine &Name = "") {
  1603. assert(V->getType()->isIntOrIntVectorTy() &&
  1604. DestTy->isIntOrIntVectorTy() &&
  1605. "Can only sign extend/truncate integers!");
  1606. Type *VTy = V->getType();
  1607. if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
  1608. return CreateSExt(V, DestTy, Name);
  1609. if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
  1610. return CreateTrunc(V, DestTy, Name);
  1611. return V;
  1612. }
  1613. Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = "") {
  1614. if (IsFPConstrained)
  1615. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptoui,
  1616. V, DestTy, nullptr, Name);
  1617. return CreateCast(Instruction::FPToUI, V, DestTy, Name);
  1618. }
  1619. Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = "") {
  1620. if (IsFPConstrained)
  1621. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptosi,
  1622. V, DestTy, nullptr, Name);
  1623. return CreateCast(Instruction::FPToSI, V, DestTy, Name);
  1624. }
  1625. Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
  1626. if (IsFPConstrained)
  1627. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_uitofp,
  1628. V, DestTy, nullptr, Name);
  1629. return CreateCast(Instruction::UIToFP, V, DestTy, Name);
  1630. }
  1631. Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
  1632. if (IsFPConstrained)
  1633. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_sitofp,
  1634. V, DestTy, nullptr, Name);
  1635. return CreateCast(Instruction::SIToFP, V, DestTy, Name);
  1636. }
  1637. Value *CreateFPTrunc(Value *V, Type *DestTy,
  1638. const Twine &Name = "") {
  1639. if (IsFPConstrained)
  1640. return CreateConstrainedFPCast(
  1641. Intrinsic::experimental_constrained_fptrunc, V, DestTy, nullptr,
  1642. Name);
  1643. return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
  1644. }
  1645. Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
  1646. if (IsFPConstrained)
  1647. return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fpext,
  1648. V, DestTy, nullptr, Name);
  1649. return CreateCast(Instruction::FPExt, V, DestTy, Name);
  1650. }
  1651. Value *CreatePtrToInt(Value *V, Type *DestTy,
  1652. const Twine &Name = "") {
  1653. return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
  1654. }
  1655. Value *CreateIntToPtr(Value *V, Type *DestTy,
  1656. const Twine &Name = "") {
  1657. return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
  1658. }
  1659. Value *CreateBitCast(Value *V, Type *DestTy,
  1660. const Twine &Name = "") {
  1661. return CreateCast(Instruction::BitCast, V, DestTy, Name);
  1662. }
  1663. Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
  1664. const Twine &Name = "") {
  1665. return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
  1666. }
  1667. Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
  1668. const Twine &Name = "") {
  1669. if (V->getType() == DestTy)
  1670. return V;
  1671. if (auto *VC = dyn_cast<Constant>(V))
  1672. return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
  1673. return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
  1674. }
  1675. Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
  1676. const Twine &Name = "") {
  1677. if (V->getType() == DestTy)
  1678. return V;
  1679. if (auto *VC = dyn_cast<Constant>(V))
  1680. return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
  1681. return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
  1682. }
  1683. Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
  1684. const Twine &Name = "") {
  1685. if (V->getType() == DestTy)
  1686. return V;
  1687. if (auto *VC = dyn_cast<Constant>(V))
  1688. return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
  1689. return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
  1690. }
  1691. Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
  1692. const Twine &Name = "") {
  1693. if (V->getType() == DestTy)
  1694. return V;
  1695. if (auto *VC = dyn_cast<Constant>(V))
  1696. return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
  1697. return Insert(CastInst::Create(Op, V, DestTy), Name);
  1698. }
  1699. Value *CreatePointerCast(Value *V, Type *DestTy,
  1700. const Twine &Name = "") {
  1701. if (V->getType() == DestTy)
  1702. return V;
  1703. if (auto *VC = dyn_cast<Constant>(V))
  1704. return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
  1705. return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
  1706. }
  1707. Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
  1708. const Twine &Name = "") {
  1709. if (V->getType() == DestTy)
  1710. return V;
  1711. if (auto *VC = dyn_cast<Constant>(V)) {
  1712. return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
  1713. Name);
  1714. }
  1715. return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
  1716. Name);
  1717. }
  1718. Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
  1719. const Twine &Name = "") {
  1720. if (V->getType() == DestTy)
  1721. return V;
  1722. if (auto *VC = dyn_cast<Constant>(V))
  1723. return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
  1724. return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
  1725. }
  1726. Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
  1727. const Twine &Name = "") {
  1728. if (V->getType() == DestTy)
  1729. return V;
  1730. if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy())
  1731. return CreatePtrToInt(V, DestTy, Name);
  1732. if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy())
  1733. return CreateIntToPtr(V, DestTy, Name);
  1734. return CreateBitCast(V, DestTy, Name);
  1735. }
  1736. Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
  1737. if (V->getType() == DestTy)
  1738. return V;
  1739. if (auto *VC = dyn_cast<Constant>(V))
  1740. return Insert(Folder.CreateFPCast(VC, DestTy), Name);
  1741. return Insert(CastInst::CreateFPCast(V, DestTy), Name);
  1742. }
  1743. CallInst *CreateConstrainedFPCast(
  1744. Intrinsic::ID ID, Value *V, Type *DestTy,
  1745. Instruction *FMFSource = nullptr, const Twine &Name = "",
  1746. MDNode *FPMathTag = nullptr,
  1747. Optional<RoundingMode> Rounding = None,
  1748. Optional<fp::ExceptionBehavior> Except = None);
  1749. // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
  1750. // compile time error, instead of converting the string to bool for the
  1751. // isSigned parameter.
  1752. Value *CreateIntCast(Value *, Type *, const char *) = delete;
  1753. //===--------------------------------------------------------------------===//
  1754. // Instruction creation methods: Compare Instructions
  1755. //===--------------------------------------------------------------------===//
  1756. Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
  1757. return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
  1758. }
  1759. Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1760. return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
  1761. }
  1762. Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1763. return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
  1764. }
  1765. Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1766. return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
  1767. }
  1768. Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1769. return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
  1770. }
  1771. Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1772. return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
  1773. }
  1774. Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1775. return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
  1776. }
  1777. Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1778. return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
  1779. }
  1780. Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
  1781. return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
  1782. }
  1783. Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
  1784. return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
  1785. }
  1786. Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
  1787. MDNode *FPMathTag = nullptr) {
  1788. return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
  1789. }
  1790. Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
  1791. MDNode *FPMathTag = nullptr) {
  1792. return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
  1793. }
  1794. Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
  1795. MDNode *FPMathTag = nullptr) {
  1796. return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
  1797. }
  1798. Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
  1799. MDNode *FPMathTag = nullptr) {
  1800. return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
  1801. }
  1802. Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
  1803. MDNode *FPMathTag = nullptr) {
  1804. return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
  1805. }
  1806. Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
  1807. MDNode *FPMathTag = nullptr) {
  1808. return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
  1809. }
  1810. Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
  1811. MDNode *FPMathTag = nullptr) {
  1812. return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
  1813. }
  1814. Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
  1815. MDNode *FPMathTag = nullptr) {
  1816. return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
  1817. }
  1818. Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
  1819. MDNode *FPMathTag = nullptr) {
  1820. return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
  1821. }
  1822. Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
  1823. MDNode *FPMathTag = nullptr) {
  1824. return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
  1825. }
  1826. Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
  1827. MDNode *FPMathTag = nullptr) {
  1828. return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
  1829. }
  1830. Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
  1831. MDNode *FPMathTag = nullptr) {
  1832. return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
  1833. }
  1834. Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
  1835. MDNode *FPMathTag = nullptr) {
  1836. return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
  1837. }
  1838. Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
  1839. MDNode *FPMathTag = nullptr) {
  1840. return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
  1841. }
  1842. Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1843. const Twine &Name = "") {
  1844. if (auto *V = Folder.FoldICmp(P, LHS, RHS))
  1845. return V;
  1846. return Insert(new ICmpInst(P, LHS, RHS), Name);
  1847. }
  1848. // Create a quiet floating-point comparison (i.e. one that raises an FP
  1849. // exception only in the case where an input is a signaling NaN).
  1850. // Note that this differs from CreateFCmpS only if IsFPConstrained is true.
  1851. Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1852. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1853. return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, false);
  1854. }
  1855. Value *CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
  1856. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1857. return CmpInst::isFPPredicate(Pred)
  1858. ? CreateFCmp(Pred, LHS, RHS, Name, FPMathTag)
  1859. : CreateICmp(Pred, LHS, RHS, Name);
  1860. }
  1861. // Create a signaling floating-point comparison (i.e. one that raises an FP
  1862. // exception whenever an input is any NaN, signaling or quiet).
  1863. // Note that this differs from CreateFCmp only if IsFPConstrained is true.
  1864. Value *CreateFCmpS(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1865. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1866. return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, true);
  1867. }
  1868. private:
  1869. // Helper routine to create either a signaling or a quiet FP comparison.
  1870. Value *CreateFCmpHelper(CmpInst::Predicate P, Value *LHS, Value *RHS,
  1871. const Twine &Name, MDNode *FPMathTag,
  1872. bool IsSignaling);
  1873. public:
  1874. CallInst *CreateConstrainedFPCmp(
  1875. Intrinsic::ID ID, CmpInst::Predicate P, Value *L, Value *R,
  1876. const Twine &Name = "", Optional<fp::ExceptionBehavior> Except = None);
  1877. //===--------------------------------------------------------------------===//
  1878. // Instruction creation methods: Other Instructions
  1879. //===--------------------------------------------------------------------===//
  1880. PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
  1881. const Twine &Name = "") {
  1882. PHINode *Phi = PHINode::Create(Ty, NumReservedValues);
  1883. if (isa<FPMathOperator>(Phi))
  1884. setFPAttrs(Phi, nullptr /* MDNode* */, FMF);
  1885. return Insert(Phi, Name);
  1886. }
  1887. CallInst *CreateCall(FunctionType *FTy, Value *Callee,
  1888. ArrayRef<Value *> Args = None, const Twine &Name = "",
  1889. MDNode *FPMathTag = nullptr) {
  1890. CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
  1891. if (IsFPConstrained)
  1892. setConstrainedFPCallAttr(CI);
  1893. if (isa<FPMathOperator>(CI))
  1894. setFPAttrs(CI, FPMathTag, FMF);
  1895. return Insert(CI, Name);
  1896. }
  1897. CallInst *CreateCall(FunctionType *FTy, Value *Callee, ArrayRef<Value *> Args,
  1898. ArrayRef<OperandBundleDef> OpBundles,
  1899. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1900. CallInst *CI = CallInst::Create(FTy, Callee, Args, OpBundles);
  1901. if (IsFPConstrained)
  1902. setConstrainedFPCallAttr(CI);
  1903. if (isa<FPMathOperator>(CI))
  1904. setFPAttrs(CI, FPMathTag, FMF);
  1905. return Insert(CI, Name);
  1906. }
  1907. CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args = None,
  1908. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1909. return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args, Name,
  1910. FPMathTag);
  1911. }
  1912. CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args,
  1913. ArrayRef<OperandBundleDef> OpBundles,
  1914. const Twine &Name = "", MDNode *FPMathTag = nullptr) {
  1915. return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args,
  1916. OpBundles, Name, FPMathTag);
  1917. }
  1918. CallInst *CreateConstrainedFPCall(
  1919. Function *Callee, ArrayRef<Value *> Args, const Twine &Name = "",
  1920. Optional<RoundingMode> Rounding = None,
  1921. Optional<fp::ExceptionBehavior> Except = None);
  1922. Value *CreateSelect(Value *C, Value *True, Value *False,
  1923. const Twine &Name = "", Instruction *MDFrom = nullptr);
  1924. VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
  1925. return Insert(new VAArgInst(List, Ty), Name);
  1926. }
  1927. Value *CreateExtractElement(Value *Vec, Value *Idx,
  1928. const Twine &Name = "") {
  1929. if (auto *VC = dyn_cast<Constant>(Vec))
  1930. if (auto *IC = dyn_cast<Constant>(Idx))
  1931. return Insert(Folder.CreateExtractElement(VC, IC), Name);
  1932. return Insert(ExtractElementInst::Create(Vec, Idx), Name);
  1933. }
  1934. Value *CreateExtractElement(Value *Vec, uint64_t Idx,
  1935. const Twine &Name = "") {
  1936. return CreateExtractElement(Vec, getInt64(Idx), Name);
  1937. }
  1938. Value *CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx,
  1939. const Twine &Name = "") {
  1940. return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name);
  1941. }
  1942. Value *CreateInsertElement(Type *VecTy, Value *NewElt, uint64_t Idx,
  1943. const Twine &Name = "") {
  1944. return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name);
  1945. }
  1946. Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
  1947. const Twine &Name = "") {
  1948. if (auto *VC = dyn_cast<Constant>(Vec))
  1949. if (auto *NC = dyn_cast<Constant>(NewElt))
  1950. if (auto *IC = dyn_cast<Constant>(Idx))
  1951. return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
  1952. return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
  1953. }
  1954. Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
  1955. const Twine &Name = "") {
  1956. return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
  1957. }
  1958. Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
  1959. const Twine &Name = "") {
  1960. SmallVector<int, 16> IntMask;
  1961. ShuffleVectorInst::getShuffleMask(cast<Constant>(Mask), IntMask);
  1962. return CreateShuffleVector(V1, V2, IntMask, Name);
  1963. }
  1964. LLVM_ATTRIBUTE_DEPRECATED(Value *CreateShuffleVector(Value *V1, Value *V2,
  1965. ArrayRef<uint32_t> Mask,
  1966. const Twine &Name = ""),
  1967. "Pass indices as 'int' instead") {
  1968. SmallVector<int, 16> IntMask;
  1969. IntMask.assign(Mask.begin(), Mask.end());
  1970. return CreateShuffleVector(V1, V2, IntMask, Name);
  1971. }
  1972. /// See class ShuffleVectorInst for a description of the mask representation.
  1973. Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask,
  1974. const Twine &Name = "") {
  1975. if (auto *V1C = dyn_cast<Constant>(V1))
  1976. if (auto *V2C = dyn_cast<Constant>(V2))
  1977. return Insert(Folder.CreateShuffleVector(V1C, V2C, Mask), Name);
  1978. return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
  1979. }
  1980. /// Create a unary shuffle. The second vector operand of the IR instruction
  1981. /// is poison.
  1982. Value *CreateShuffleVector(Value *V, ArrayRef<int> Mask,
  1983. const Twine &Name = "") {
  1984. return CreateShuffleVector(V, PoisonValue::get(V->getType()), Mask, Name);
  1985. }
  1986. Value *CreateExtractValue(Value *Agg,
  1987. ArrayRef<unsigned> Idxs,
  1988. const Twine &Name = "") {
  1989. if (auto *AggC = dyn_cast<Constant>(Agg))
  1990. return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
  1991. return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
  1992. }
  1993. Value *CreateInsertValue(Value *Agg, Value *Val,
  1994. ArrayRef<unsigned> Idxs,
  1995. const Twine &Name = "") {
  1996. if (auto *AggC = dyn_cast<Constant>(Agg))
  1997. if (auto *ValC = dyn_cast<Constant>(Val))
  1998. return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
  1999. return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
  2000. }
  2001. LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
  2002. const Twine &Name = "") {
  2003. return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
  2004. }
  2005. Value *CreateFreeze(Value *V, const Twine &Name = "") {
  2006. return Insert(new FreezeInst(V), Name);
  2007. }
  2008. //===--------------------------------------------------------------------===//
  2009. // Utility creation methods
  2010. //===--------------------------------------------------------------------===//
  2011. /// Return an i1 value testing if \p Arg is null.
  2012. Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
  2013. return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
  2014. Name);
  2015. }
  2016. /// Return an i1 value testing if \p Arg is not null.
  2017. Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
  2018. return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
  2019. Name);
  2020. }
  2021. /// Return the i64 difference between two pointer values, dividing out
  2022. /// the size of the pointed-to objects.
  2023. ///
  2024. /// This is intended to implement C-style pointer subtraction. As such, the
  2025. /// pointers must be appropriately aligned for their element types and
  2026. /// pointing into the same object.
  2027. Value *CreatePtrDiff(Type *ElemTy, Value *LHS, Value *RHS,
  2028. const Twine &Name = "");
  2029. /// Create a launder.invariant.group intrinsic call. If Ptr type is
  2030. /// different from pointer to i8, it's casted to pointer to i8 in the same
  2031. /// address space before call and casted back to Ptr type after call.
  2032. Value *CreateLaunderInvariantGroup(Value *Ptr);
  2033. /// \brief Create a strip.invariant.group intrinsic call. If Ptr type is
  2034. /// different from pointer to i8, it's casted to pointer to i8 in the same
  2035. /// address space before call and casted back to Ptr type after call.
  2036. Value *CreateStripInvariantGroup(Value *Ptr);
  2037. /// Return a vector value that contains the vector V reversed
  2038. Value *CreateVectorReverse(Value *V, const Twine &Name = "");
  2039. /// Return a vector splice intrinsic if using scalable vectors, otherwise
  2040. /// return a shufflevector. If the immediate is positive, a vector is
  2041. /// extracted from concat(V1, V2), starting at Imm. If the immediate
  2042. /// is negative, we extract -Imm elements from V1 and the remaining
  2043. /// elements from V2. Imm is a signed integer in the range
  2044. /// -VL <= Imm < VL (where VL is the runtime vector length of the
  2045. /// source/result vector)
  2046. Value *CreateVectorSplice(Value *V1, Value *V2, int64_t Imm,
  2047. const Twine &Name = "");
  2048. /// Return a vector value that contains \arg V broadcasted to \p
  2049. /// NumElts elements.
  2050. Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "");
  2051. /// Return a vector value that contains \arg V broadcasted to \p
  2052. /// EC elements.
  2053. Value *CreateVectorSplat(ElementCount EC, Value *V, const Twine &Name = "");
  2054. /// Return a value that has been extracted from a larger integer type.
  2055. Value *CreateExtractInteger(const DataLayout &DL, Value *From,
  2056. IntegerType *ExtractedTy, uint64_t Offset,
  2057. const Twine &Name);
  2058. Value *CreatePreserveArrayAccessIndex(Type *ElTy, Value *Base,
  2059. unsigned Dimension, unsigned LastIndex,
  2060. MDNode *DbgInfo);
  2061. Value *CreatePreserveUnionAccessIndex(Value *Base, unsigned FieldIndex,
  2062. MDNode *DbgInfo);
  2063. Value *CreatePreserveStructAccessIndex(Type *ElTy, Value *Base,
  2064. unsigned Index, unsigned FieldIndex,
  2065. MDNode *DbgInfo);
  2066. private:
  2067. /// Helper function that creates an assume intrinsic call that
  2068. /// represents an alignment assumption on the provided pointer \p PtrValue
  2069. /// with offset \p OffsetValue and alignment value \p AlignValue.
  2070. CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL,
  2071. Value *PtrValue, Value *AlignValue,
  2072. Value *OffsetValue);
  2073. public:
  2074. /// Create an assume intrinsic call that represents an alignment
  2075. /// assumption on the provided pointer.
  2076. ///
  2077. /// An optional offset can be provided, and if it is provided, the offset
  2078. /// must be subtracted from the provided pointer to get the pointer with the
  2079. /// specified alignment.
  2080. CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
  2081. unsigned Alignment,
  2082. Value *OffsetValue = nullptr);
  2083. /// Create an assume intrinsic call that represents an alignment
  2084. /// assumption on the provided pointer.
  2085. ///
  2086. /// An optional offset can be provided, and if it is provided, the offset
  2087. /// must be subtracted from the provided pointer to get the pointer with the
  2088. /// specified alignment.
  2089. ///
  2090. /// This overload handles the condition where the Alignment is dependent
  2091. /// on an existing value rather than a static value.
  2092. CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
  2093. Value *Alignment,
  2094. Value *OffsetValue = nullptr);
  2095. };
  2096. /// This provides a uniform API for creating instructions and inserting
  2097. /// them into a basic block: either at the end of a BasicBlock, or at a specific
  2098. /// iterator location in a block.
  2099. ///
  2100. /// Note that the builder does not expose the full generality of LLVM
  2101. /// instructions. For access to extra instruction properties, use the mutators
  2102. /// (e.g. setVolatile) on the instructions after they have been
  2103. /// created. Convenience state exists to specify fast-math flags and fp-math
  2104. /// tags.
  2105. ///
  2106. /// The first template argument specifies a class to use for creating constants.
  2107. /// This defaults to creating minimally folded constants. The second template
  2108. /// argument allows clients to specify custom insertion hooks that are called on
  2109. /// every newly created insertion.
  2110. template <typename FolderTy = ConstantFolder,
  2111. typename InserterTy = IRBuilderDefaultInserter>
  2112. class IRBuilder : public IRBuilderBase {
  2113. private:
  2114. FolderTy Folder;
  2115. InserterTy Inserter;
  2116. public:
  2117. IRBuilder(LLVMContext &C, FolderTy Folder, InserterTy Inserter = InserterTy(),
  2118. MDNode *FPMathTag = nullptr,
  2119. ArrayRef<OperandBundleDef> OpBundles = None)
  2120. : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles),
  2121. Folder(Folder), Inserter(Inserter) {}
  2122. explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
  2123. ArrayRef<OperandBundleDef> OpBundles = None)
  2124. : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles) {}
  2125. explicit IRBuilder(BasicBlock *TheBB, FolderTy Folder,
  2126. MDNode *FPMathTag = nullptr,
  2127. ArrayRef<OperandBundleDef> OpBundles = None)
  2128. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2129. FPMathTag, OpBundles), Folder(Folder) {
  2130. SetInsertPoint(TheBB);
  2131. }
  2132. explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
  2133. ArrayRef<OperandBundleDef> OpBundles = None)
  2134. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2135. FPMathTag, OpBundles) {
  2136. SetInsertPoint(TheBB);
  2137. }
  2138. explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
  2139. ArrayRef<OperandBundleDef> OpBundles = None)
  2140. : IRBuilderBase(IP->getContext(), this->Folder, this->Inserter,
  2141. FPMathTag, OpBundles) {
  2142. SetInsertPoint(IP);
  2143. }
  2144. IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, FolderTy Folder,
  2145. MDNode *FPMathTag = nullptr,
  2146. ArrayRef<OperandBundleDef> OpBundles = None)
  2147. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2148. FPMathTag, OpBundles), Folder(Folder) {
  2149. SetInsertPoint(TheBB, IP);
  2150. }
  2151. IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
  2152. MDNode *FPMathTag = nullptr,
  2153. ArrayRef<OperandBundleDef> OpBundles = None)
  2154. : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
  2155. FPMathTag, OpBundles) {
  2156. SetInsertPoint(TheBB, IP);
  2157. }
  2158. /// Avoid copying the full IRBuilder. Prefer using InsertPointGuard
  2159. /// or FastMathFlagGuard instead.
  2160. IRBuilder(const IRBuilder &) = delete;
  2161. InserterTy &getInserter() { return Inserter; }
  2162. };
  2163. // Create wrappers for C Binding types (see CBindingWrapping.h).
  2164. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
  2165. } // end namespace llvm
  2166. #endif // LLVM_IR_IRBUILDER_H
  2167. #ifdef __GNUC__
  2168. #pragma GCC diagnostic pop
  2169. #endif