FastISel.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255
  1. //===- FastISel.cpp - Implementation of the FastISel class ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains the implementation of the FastISel class.
  11. //
  12. // "Fast" instruction selection is designed to emit very poor code quickly.
  13. // Also, it is not designed to be able to do much lowering, so most illegal
  14. // types (e.g. i64 on 32-bit targets) and operations are not supported. It is
  15. // also not intended to be able to do much optimization, except in a few cases
  16. // where doing optimizations reduces overall compile time. For example, folding
  17. // constants into immediate fields is often done, because it's cheap and it
  18. // reduces the number of instructions later phases have to examine.
  19. //
  20. // "Fast" instruction selection is able to fail gracefully and transfer
  21. // control to the SelectionDAG selector for operations that it doesn't
  22. // support. In many cases, this allows us to avoid duplicating a lot of
  23. // the complicated lowering logic that SelectionDAG currently has.
  24. //
  25. // The intended use for "fast" instruction selection is "-O0" mode
  26. // compilation, where the quality of the generated code is irrelevant when
  27. // weighed against the speed at which the code can be generated. Also,
  28. // at -O0, the LLVM optimizers are not running, and this makes the
  29. // compile time of codegen a much higher portion of the overall compile
  30. // time. Despite its limitations, "fast" instruction selection is able to
  31. // handle enough code on its own to provide noticeable overall speedups
  32. // in -O0 compiles.
  33. //
  34. // Basic operations are supported in a target-independent way, by reading
  35. // the same instruction descriptions that the SelectionDAG selector reads,
  36. // and identifying simple arithmetic operations that can be directly selected
  37. // from simple operators. More complicated operations currently require
  38. // target-specific code.
  39. //
  40. //===----------------------------------------------------------------------===//
  41. #include "llvm/CodeGen/FastISel.h"
  42. #include "llvm/ADT/APFloat.h"
  43. #include "llvm/ADT/APSInt.h"
  44. #include "llvm/ADT/DenseMap.h"
  45. #include "llvm/ADT/Optional.h"
  46. #include "llvm/ADT/SmallPtrSet.h"
  47. #include "llvm/ADT/SmallString.h"
  48. #include "llvm/ADT/SmallVector.h"
  49. #include "llvm/ADT/Statistic.h"
  50. #include "llvm/Analysis/BranchProbabilityInfo.h"
  51. #include "llvm/Analysis/TargetLibraryInfo.h"
  52. #include "llvm/CodeGen/Analysis.h"
  53. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  54. #include "llvm/CodeGen/ISDOpcodes.h"
  55. #include "llvm/CodeGen/MachineBasicBlock.h"
  56. #include "llvm/CodeGen/MachineFrameInfo.h"
  57. #include "llvm/CodeGen/MachineInstr.h"
  58. #include "llvm/CodeGen/MachineInstrBuilder.h"
  59. #include "llvm/CodeGen/MachineMemOperand.h"
  60. #include "llvm/CodeGen/MachineModuleInfo.h"
  61. #include "llvm/CodeGen/MachineOperand.h"
  62. #include "llvm/CodeGen/MachineRegisterInfo.h"
  63. #include "llvm/CodeGen/MachineValueType.h"
  64. #include "llvm/CodeGen/StackMaps.h"
  65. #include "llvm/CodeGen/TargetInstrInfo.h"
  66. #include "llvm/CodeGen/TargetLowering.h"
  67. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  68. #include "llvm/CodeGen/ValueTypes.h"
  69. #include "llvm/IR/Argument.h"
  70. #include "llvm/IR/Attributes.h"
  71. #include "llvm/IR/BasicBlock.h"
  72. #include "llvm/IR/CallSite.h"
  73. #include "llvm/IR/CallingConv.h"
  74. #include "llvm/IR/Constant.h"
  75. #include "llvm/IR/Constants.h"
  76. #include "llvm/IR/DataLayout.h"
  77. #include "llvm/IR/DebugInfo.h"
  78. #include "llvm/IR/DebugLoc.h"
  79. #include "llvm/IR/DerivedTypes.h"
  80. #include "llvm/IR/Function.h"
  81. #include "llvm/IR/GetElementPtrTypeIterator.h"
  82. #include "llvm/IR/GlobalValue.h"
  83. #include "llvm/IR/InlineAsm.h"
  84. #include "llvm/IR/InstrTypes.h"
  85. #include "llvm/IR/Instruction.h"
  86. #include "llvm/IR/Instructions.h"
  87. #include "llvm/IR/IntrinsicInst.h"
  88. #include "llvm/IR/LLVMContext.h"
  89. #include "llvm/IR/Mangler.h"
  90. #include "llvm/IR/Metadata.h"
  91. #include "llvm/IR/Operator.h"
  92. #include "llvm/IR/Type.h"
  93. #include "llvm/IR/User.h"
  94. #include "llvm/IR/Value.h"
  95. #include "llvm/MC/MCContext.h"
  96. #include "llvm/MC/MCInstrDesc.h"
  97. #include "llvm/MC/MCRegisterInfo.h"
  98. #include "llvm/Support/Casting.h"
  99. #include "llvm/Support/Debug.h"
  100. #include "llvm/Support/ErrorHandling.h"
  101. #include "llvm/Support/MathExtras.h"
  102. #include "llvm/Support/raw_ostream.h"
  103. #include "llvm/Target/TargetMachine.h"
  104. #include "llvm/Target/TargetOptions.h"
  105. #include <algorithm>
  106. #include <cassert>
  107. #include <cstdint>
  108. #include <iterator>
  109. #include <utility>
  110. using namespace llvm;
  111. #define DEBUG_TYPE "isel"
  112. STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
  113. "target-independent selector");
  114. STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
  115. "target-specific selector");
  116. STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
  117. /// Set the current block to which generated machine instructions will be
  118. /// appended, and clear the local CSE map.
  119. void FastISel::startNewBlock() {
  120. LocalValueMap.clear();
  121. // Instructions are appended to FuncInfo.MBB. If the basic block already
  122. // contains labels or copies, use the last instruction as the last local
  123. // value.
  124. EmitStartPt = nullptr;
  125. if (!FuncInfo.MBB->empty())
  126. EmitStartPt = &FuncInfo.MBB->back();
  127. LastLocalValue = EmitStartPt;
  128. }
  129. bool FastISel::lowerArguments() {
  130. if (!FuncInfo.CanLowerReturn)
  131. // Fallback to SDISel argument lowering code to deal with sret pointer
  132. // parameter.
  133. return false;
  134. if (!fastLowerArguments())
  135. return false;
  136. // Enter arguments into ValueMap for uses in non-entry BBs.
  137. for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
  138. E = FuncInfo.Fn->arg_end();
  139. I != E; ++I) {
  140. DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
  141. assert(VI != LocalValueMap.end() && "Missed an argument?");
  142. FuncInfo.ValueMap[&*I] = VI->second;
  143. }
  144. return true;
  145. }
  146. void FastISel::flushLocalValueMap() {
  147. LocalValueMap.clear();
  148. LastLocalValue = EmitStartPt;
  149. recomputeInsertPt();
  150. SavedInsertPt = FuncInfo.InsertPt;
  151. }
  152. bool FastISel::hasTrivialKill(const Value *V) {
  153. // Don't consider constants or arguments to have trivial kills.
  154. const Instruction *I = dyn_cast<Instruction>(V);
  155. if (!I)
  156. return false;
  157. // No-op casts are trivially coalesced by fast-isel.
  158. if (const auto *Cast = dyn_cast<CastInst>(I))
  159. if (Cast->isNoopCast(DL) && !hasTrivialKill(Cast->getOperand(0)))
  160. return false;
  161. // Even the value might have only one use in the LLVM IR, it is possible that
  162. // FastISel might fold the use into another instruction and now there is more
  163. // than one use at the Machine Instruction level.
  164. unsigned Reg = lookUpRegForValue(V);
  165. if (Reg && !MRI.use_empty(Reg))
  166. return false;
  167. // GEPs with all zero indices are trivially coalesced by fast-isel.
  168. if (const auto *GEP = dyn_cast<GetElementPtrInst>(I))
  169. if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
  170. return false;
  171. // Only instructions with a single use in the same basic block are considered
  172. // to have trivial kills.
  173. return I->hasOneUse() &&
  174. !(I->getOpcode() == Instruction::BitCast ||
  175. I->getOpcode() == Instruction::PtrToInt ||
  176. I->getOpcode() == Instruction::IntToPtr) &&
  177. cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
  178. }
  179. unsigned FastISel::getRegForValue(const Value *V) {
  180. EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true);
  181. // Don't handle non-simple values in FastISel.
  182. if (!RealVT.isSimple())
  183. return 0;
  184. // Ignore illegal types. We must do this before looking up the value
  185. // in ValueMap because Arguments are given virtual registers regardless
  186. // of whether FastISel can handle them.
  187. MVT VT = RealVT.getSimpleVT();
  188. if (!TLI.isTypeLegal(VT)) {
  189. // Handle integer promotions, though, because they're common and easy.
  190. if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
  191. VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
  192. else
  193. return 0;
  194. }
  195. // Look up the value to see if we already have a register for it.
  196. unsigned Reg = lookUpRegForValue(V);
  197. if (Reg)
  198. return Reg;
  199. // In bottom-up mode, just create the virtual register which will be used
  200. // to hold the value. It will be materialized later.
  201. if (isa<Instruction>(V) &&
  202. (!isa<AllocaInst>(V) ||
  203. !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
  204. return FuncInfo.InitializeRegForValue(V);
  205. SavePoint SaveInsertPt = enterLocalValueArea();
  206. // Materialize the value in a register. Emit any instructions in the
  207. // local value area.
  208. Reg = materializeRegForValue(V, VT);
  209. leaveLocalValueArea(SaveInsertPt);
  210. return Reg;
  211. }
  212. unsigned FastISel::materializeConstant(const Value *V, MVT VT) {
  213. unsigned Reg = 0;
  214. if (const auto *CI = dyn_cast<ConstantInt>(V)) {
  215. if (CI->getValue().getActiveBits() <= 64)
  216. Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
  217. } else if (isa<AllocaInst>(V))
  218. Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
  219. else if (isa<ConstantPointerNull>(V))
  220. // Translate this as an integer zero so that it can be
  221. // local-CSE'd with actual integer zeros.
  222. Reg = getRegForValue(
  223. Constant::getNullValue(DL.getIntPtrType(V->getContext())));
  224. else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
  225. if (CF->isNullValue())
  226. Reg = fastMaterializeFloatZero(CF);
  227. else
  228. // Try to emit the constant directly.
  229. Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
  230. if (!Reg) {
  231. // Try to emit the constant by using an integer constant with a cast.
  232. const APFloat &Flt = CF->getValueAPF();
  233. EVT IntVT = TLI.getPointerTy(DL);
  234. uint32_t IntBitWidth = IntVT.getSizeInBits();
  235. APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false);
  236. bool isExact;
  237. (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact);
  238. if (isExact) {
  239. unsigned IntegerReg =
  240. getRegForValue(ConstantInt::get(V->getContext(), SIntVal));
  241. if (IntegerReg != 0)
  242. Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg,
  243. /*Kill=*/false);
  244. }
  245. }
  246. } else if (const auto *Op = dyn_cast<Operator>(V)) {
  247. if (!selectOperator(Op, Op->getOpcode()))
  248. if (!isa<Instruction>(Op) ||
  249. !fastSelectInstruction(cast<Instruction>(Op)))
  250. return 0;
  251. Reg = lookUpRegForValue(Op);
  252. } else if (isa<UndefValue>(V)) {
  253. Reg = createResultReg(TLI.getRegClassFor(VT));
  254. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  255. TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
  256. }
  257. return Reg;
  258. }
  259. /// Helper for getRegForValue. This function is called when the value isn't
  260. /// already available in a register and must be materialized with new
  261. /// instructions.
  262. unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
  263. unsigned Reg = 0;
  264. // Give the target-specific code a try first.
  265. if (isa<Constant>(V))
  266. Reg = fastMaterializeConstant(cast<Constant>(V));
  267. // If target-specific code couldn't or didn't want to handle the value, then
  268. // give target-independent code a try.
  269. if (!Reg)
  270. Reg = materializeConstant(V, VT);
  271. // Don't cache constant materializations in the general ValueMap.
  272. // To do so would require tracking what uses they dominate.
  273. if (Reg) {
  274. LocalValueMap[V] = Reg;
  275. LastLocalValue = MRI.getVRegDef(Reg);
  276. }
  277. return Reg;
  278. }
  279. unsigned FastISel::lookUpRegForValue(const Value *V) {
  280. // Look up the value to see if we already have a register for it. We
  281. // cache values defined by Instructions across blocks, and other values
  282. // only locally. This is because Instructions already have the SSA
  283. // def-dominates-use requirement enforced.
  284. DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
  285. if (I != FuncInfo.ValueMap.end())
  286. return I->second;
  287. return LocalValueMap[V];
  288. }
  289. void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
  290. if (!isa<Instruction>(I)) {
  291. LocalValueMap[I] = Reg;
  292. return;
  293. }
  294. unsigned &AssignedReg = FuncInfo.ValueMap[I];
  295. if (AssignedReg == 0)
  296. // Use the new register.
  297. AssignedReg = Reg;
  298. else if (Reg != AssignedReg) {
  299. // Arrange for uses of AssignedReg to be replaced by uses of Reg.
  300. for (unsigned i = 0; i < NumRegs; i++)
  301. FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
  302. AssignedReg = Reg;
  303. }
  304. }
  305. std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
  306. unsigned IdxN = getRegForValue(Idx);
  307. if (IdxN == 0)
  308. // Unhandled operand. Halt "fast" selection and bail.
  309. return std::pair<unsigned, bool>(0, false);
  310. bool IdxNIsKill = hasTrivialKill(Idx);
  311. // If the index is smaller or larger than intptr_t, truncate or extend it.
  312. MVT PtrVT = TLI.getPointerTy(DL);
  313. EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
  314. if (IdxVT.bitsLT(PtrVT)) {
  315. IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN,
  316. IdxNIsKill);
  317. IdxNIsKill = true;
  318. } else if (IdxVT.bitsGT(PtrVT)) {
  319. IdxN =
  320. fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill);
  321. IdxNIsKill = true;
  322. }
  323. return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
  324. }
  325. void FastISel::recomputeInsertPt() {
  326. if (getLastLocalValue()) {
  327. FuncInfo.InsertPt = getLastLocalValue();
  328. FuncInfo.MBB = FuncInfo.InsertPt->getParent();
  329. ++FuncInfo.InsertPt;
  330. } else
  331. FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
  332. // Now skip past any EH_LABELs, which must remain at the beginning.
  333. while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
  334. FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
  335. ++FuncInfo.InsertPt;
  336. }
  337. void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
  338. MachineBasicBlock::iterator E) {
  339. assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 &&
  340. "Invalid iterator!");
  341. while (I != E) {
  342. MachineInstr *Dead = &*I;
  343. ++I;
  344. Dead->eraseFromParent();
  345. ++NumFastIselDead;
  346. }
  347. recomputeInsertPt();
  348. }
  349. FastISel::SavePoint FastISel::enterLocalValueArea() {
  350. MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
  351. DebugLoc OldDL = DbgLoc;
  352. recomputeInsertPt();
  353. DbgLoc = DebugLoc();
  354. SavePoint SP = {OldInsertPt, OldDL};
  355. return SP;
  356. }
  357. void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
  358. if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
  359. LastLocalValue = &*std::prev(FuncInfo.InsertPt);
  360. // Restore the previous insert position.
  361. FuncInfo.InsertPt = OldInsertPt.InsertPt;
  362. DbgLoc = OldInsertPt.DL;
  363. }
  364. bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
  365. EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
  366. if (VT == MVT::Other || !VT.isSimple())
  367. // Unhandled type. Halt "fast" selection and bail.
  368. return false;
  369. // We only handle legal types. For example, on x86-32 the instruction
  370. // selector contains all of the 64-bit instructions from x86-64,
  371. // under the assumption that i64 won't be used if the target doesn't
  372. // support it.
  373. if (!TLI.isTypeLegal(VT)) {
  374. // MVT::i1 is special. Allow AND, OR, or XOR because they
  375. // don't require additional zeroing, which makes them easy.
  376. if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
  377. ISDOpcode == ISD::XOR))
  378. VT = TLI.getTypeToTransformTo(I->getContext(), VT);
  379. else
  380. return false;
  381. }
  382. // Check if the first operand is a constant, and handle it as "ri". At -O0,
  383. // we don't have anything that canonicalizes operand order.
  384. if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
  385. if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
  386. unsigned Op1 = getRegForValue(I->getOperand(1));
  387. if (!Op1)
  388. return false;
  389. bool Op1IsKill = hasTrivialKill(I->getOperand(1));
  390. unsigned ResultReg =
  391. fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill,
  392. CI->getZExtValue(), VT.getSimpleVT());
  393. if (!ResultReg)
  394. return false;
  395. // We successfully emitted code for the given LLVM Instruction.
  396. updateValueMap(I, ResultReg);
  397. return true;
  398. }
  399. unsigned Op0 = getRegForValue(I->getOperand(0));
  400. if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
  401. return false;
  402. bool Op0IsKill = hasTrivialKill(I->getOperand(0));
  403. // Check if the second operand is a constant and handle it appropriately.
  404. if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
  405. uint64_t Imm = CI->getSExtValue();
  406. // Transform "sdiv exact X, 8" -> "sra X, 3".
  407. if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
  408. cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
  409. Imm = Log2_64(Imm);
  410. ISDOpcode = ISD::SRA;
  411. }
  412. // Transform "urem x, pow2" -> "and x, pow2-1".
  413. if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
  414. isPowerOf2_64(Imm)) {
  415. --Imm;
  416. ISDOpcode = ISD::AND;
  417. }
  418. unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
  419. Op0IsKill, Imm, VT.getSimpleVT());
  420. if (!ResultReg)
  421. return false;
  422. // We successfully emitted code for the given LLVM Instruction.
  423. updateValueMap(I, ResultReg);
  424. return true;
  425. }
  426. unsigned Op1 = getRegForValue(I->getOperand(1));
  427. if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
  428. return false;
  429. bool Op1IsKill = hasTrivialKill(I->getOperand(1));
  430. // Now we have both operands in registers. Emit the instruction.
  431. unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
  432. ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill);
  433. if (!ResultReg)
  434. // Target-specific code wasn't able to find a machine opcode for
  435. // the given ISD opcode and type. Halt "fast" selection and bail.
  436. return false;
  437. // We successfully emitted code for the given LLVM Instruction.
  438. updateValueMap(I, ResultReg);
  439. return true;
  440. }
  441. bool FastISel::selectGetElementPtr(const User *I) {
  442. unsigned N = getRegForValue(I->getOperand(0));
  443. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  444. return false;
  445. bool NIsKill = hasTrivialKill(I->getOperand(0));
  446. // Keep a running tab of the total offset to coalesce multiple N = N + Offset
  447. // into a single N = N + TotalOffset.
  448. uint64_t TotalOffs = 0;
  449. // FIXME: What's a good SWAG number for MaxOffs?
  450. uint64_t MaxOffs = 2048;
  451. MVT VT = TLI.getPointerTy(DL);
  452. for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I);
  453. GTI != E; ++GTI) {
  454. const Value *Idx = GTI.getOperand();
  455. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  456. uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue();
  457. if (Field) {
  458. // N = N + Offset
  459. TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
  460. if (TotalOffs >= MaxOffs) {
  461. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  462. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  463. return false;
  464. NIsKill = true;
  465. TotalOffs = 0;
  466. }
  467. }
  468. } else {
  469. Type *Ty = GTI.getIndexedType();
  470. // If this is a constant subscript, handle it quickly.
  471. if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
  472. if (CI->isZero())
  473. continue;
  474. // N = N + Offset
  475. uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue();
  476. TotalOffs += DL.getTypeAllocSize(Ty) * IdxN;
  477. if (TotalOffs >= MaxOffs) {
  478. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  479. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  480. return false;
  481. NIsKill = true;
  482. TotalOffs = 0;
  483. }
  484. continue;
  485. }
  486. if (TotalOffs) {
  487. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  488. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  489. return false;
  490. NIsKill = true;
  491. TotalOffs = 0;
  492. }
  493. // N = N + Idx * ElementSize;
  494. uint64_t ElementSize = DL.getTypeAllocSize(Ty);
  495. std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
  496. unsigned IdxN = Pair.first;
  497. bool IdxNIsKill = Pair.second;
  498. if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
  499. return false;
  500. if (ElementSize != 1) {
  501. IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
  502. if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
  503. return false;
  504. IdxNIsKill = true;
  505. }
  506. N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
  507. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  508. return false;
  509. }
  510. }
  511. if (TotalOffs) {
  512. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  513. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  514. return false;
  515. }
  516. // We successfully emitted code for the given LLVM Instruction.
  517. updateValueMap(I, N);
  518. return true;
  519. }
  520. bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
  521. const CallInst *CI, unsigned StartIdx) {
  522. for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) {
  523. Value *Val = CI->getArgOperand(i);
  524. // Check for constants and encode them with a StackMaps::ConstantOp prefix.
  525. if (const auto *C = dyn_cast<ConstantInt>(Val)) {
  526. Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
  527. Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
  528. } else if (isa<ConstantPointerNull>(Val)) {
  529. Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
  530. Ops.push_back(MachineOperand::CreateImm(0));
  531. } else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
  532. // Values coming from a stack location also require a special encoding,
  533. // but that is added later on by the target specific frame index
  534. // elimination implementation.
  535. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  536. if (SI != FuncInfo.StaticAllocaMap.end())
  537. Ops.push_back(MachineOperand::CreateFI(SI->second));
  538. else
  539. return false;
  540. } else {
  541. unsigned Reg = getRegForValue(Val);
  542. if (!Reg)
  543. return false;
  544. Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
  545. }
  546. }
  547. return true;
  548. }
  549. bool FastISel::selectStackmap(const CallInst *I) {
  550. // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
  551. // [live variables...])
  552. assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
  553. "Stackmap cannot return a value.");
  554. // The stackmap intrinsic only records the live variables (the arguments
  555. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  556. // intrinsic, this won't be lowered to a function call. This means we don't
  557. // have to worry about calling conventions and target-specific lowering code.
  558. // Instead we perform the call lowering right here.
  559. //
  560. // CALLSEQ_START(0, 0...)
  561. // STACKMAP(id, nbytes, ...)
  562. // CALLSEQ_END(0, 0)
  563. //
  564. SmallVector<MachineOperand, 32> Ops;
  565. // Add the <id> and <numBytes> constants.
  566. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
  567. "Expected a constant integer.");
  568. const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
  569. Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
  570. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
  571. "Expected a constant integer.");
  572. const auto *NumBytes =
  573. cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
  574. Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
  575. // Push live variables for the stack map (skipping the first two arguments
  576. // <id> and <numBytes>).
  577. if (!addStackMapLiveVars(Ops, I, 2))
  578. return false;
  579. // We are not adding any register mask info here, because the stackmap doesn't
  580. // clobber anything.
  581. // Add scratch registers as implicit def and early clobber.
  582. CallingConv::ID CC = I->getCallingConv();
  583. const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
  584. for (unsigned i = 0; ScratchRegs[i]; ++i)
  585. Ops.push_back(MachineOperand::CreateReg(
  586. ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
  587. /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
  588. // Issue CALLSEQ_START
  589. unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
  590. auto Builder =
  591. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown));
  592. const MCInstrDesc &MCID = Builder.getInstr()->getDesc();
  593. for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I)
  594. Builder.addImm(0);
  595. // Issue STACKMAP.
  596. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  597. TII.get(TargetOpcode::STACKMAP));
  598. for (auto const &MO : Ops)
  599. MIB.add(MO);
  600. // Issue CALLSEQ_END
  601. unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
  602. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
  603. .addImm(0)
  604. .addImm(0);
  605. // Inform the Frame Information that we have a stackmap in this function.
  606. FuncInfo.MF->getFrameInfo().setHasStackMap();
  607. return true;
  608. }
  609. /// \brief Lower an argument list according to the target calling convention.
  610. ///
  611. /// This is a helper for lowering intrinsics that follow a target calling
  612. /// convention or require stack pointer adjustment. Only a subset of the
  613. /// intrinsic's operands need to participate in the calling convention.
  614. bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
  615. unsigned NumArgs, const Value *Callee,
  616. bool ForceRetVoidTy, CallLoweringInfo &CLI) {
  617. ArgListTy Args;
  618. Args.reserve(NumArgs);
  619. // Populate the argument list.
  620. ImmutableCallSite CS(CI);
  621. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) {
  622. Value *V = CI->getOperand(ArgI);
  623. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  624. ArgListEntry Entry;
  625. Entry.Val = V;
  626. Entry.Ty = V->getType();
  627. Entry.setAttributes(&CS, ArgIdx);
  628. Args.push_back(Entry);
  629. }
  630. Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
  631. : CI->getType();
  632. CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
  633. return lowerCallTo(CLI);
  634. }
  635. FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee(
  636. const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy,
  637. StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) {
  638. SmallString<32> MangledName;
  639. Mangler::getNameWithPrefix(MangledName, Target, DL);
  640. MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
  641. return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs);
  642. }
  643. bool FastISel::selectPatchpoint(const CallInst *I) {
  644. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  645. // i32 <numBytes>,
  646. // i8* <target>,
  647. // i32 <numArgs>,
  648. // [Args...],
  649. // [live variables...])
  650. CallingConv::ID CC = I->getCallingConv();
  651. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  652. bool HasDef = !I->getType()->isVoidTy();
  653. Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts();
  654. // Get the real number of arguments participating in the call <numArgs>
  655. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
  656. "Expected a constant integer.");
  657. const auto *NumArgsVal =
  658. cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
  659. unsigned NumArgs = NumArgsVal->getZExtValue();
  660. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  661. // This includes all meta-operands up to but not including CC.
  662. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  663. assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs &&
  664. "Not enough arguments provided to the patchpoint intrinsic");
  665. // For AnyRegCC the arguments are lowered later on manually.
  666. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  667. CallLoweringInfo CLI;
  668. CLI.setIsPatchPoint();
  669. if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
  670. return false;
  671. assert(CLI.Call && "No call instruction specified.");
  672. SmallVector<MachineOperand, 32> Ops;
  673. // Add an explicit result reg if we use the anyreg calling convention.
  674. if (IsAnyRegCC && HasDef) {
  675. assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
  676. CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
  677. CLI.NumResultRegs = 1;
  678. Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*IsDef=*/true));
  679. }
  680. // Add the <id> and <numBytes> constants.
  681. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
  682. "Expected a constant integer.");
  683. const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
  684. Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
  685. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
  686. "Expected a constant integer.");
  687. const auto *NumBytes =
  688. cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
  689. Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
  690. // Add the call target.
  691. if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) {
  692. uint64_t CalleeConstAddr =
  693. cast<ConstantInt>(C->getOperand(0))->getZExtValue();
  694. Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
  695. } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
  696. if (C->getOpcode() == Instruction::IntToPtr) {
  697. uint64_t CalleeConstAddr =
  698. cast<ConstantInt>(C->getOperand(0))->getZExtValue();
  699. Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
  700. } else
  701. llvm_unreachable("Unsupported ConstantExpr.");
  702. } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) {
  703. Ops.push_back(MachineOperand::CreateGA(GV, 0));
  704. } else if (isa<ConstantPointerNull>(Callee))
  705. Ops.push_back(MachineOperand::CreateImm(0));
  706. else
  707. llvm_unreachable("Unsupported callee address.");
  708. // Adjust <numArgs> to account for any arguments that have been passed on
  709. // the stack instead.
  710. unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
  711. Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
  712. // Add the calling convention
  713. Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
  714. // Add the arguments we omitted previously. The register allocator should
  715. // place these in any free register.
  716. if (IsAnyRegCC) {
  717. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
  718. unsigned Reg = getRegForValue(I->getArgOperand(i));
  719. if (!Reg)
  720. return false;
  721. Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
  722. }
  723. }
  724. // Push the arguments from the call instruction.
  725. for (auto Reg : CLI.OutRegs)
  726. Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
  727. // Push live variables for the stack map.
  728. if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
  729. return false;
  730. // Push the register mask info.
  731. Ops.push_back(MachineOperand::CreateRegMask(
  732. TRI.getCallPreservedMask(*FuncInfo.MF, CC)));
  733. // Add scratch registers as implicit def and early clobber.
  734. const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
  735. for (unsigned i = 0; ScratchRegs[i]; ++i)
  736. Ops.push_back(MachineOperand::CreateReg(
  737. ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
  738. /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
  739. // Add implicit defs (return values).
  740. for (auto Reg : CLI.InRegs)
  741. Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/true,
  742. /*IsImpl=*/true));
  743. // Insert the patchpoint instruction before the call generated by the target.
  744. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc,
  745. TII.get(TargetOpcode::PATCHPOINT));
  746. for (auto &MO : Ops)
  747. MIB.add(MO);
  748. MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
  749. // Delete the original call instruction.
  750. CLI.Call->eraseFromParent();
  751. // Inform the Frame Information that we have a patchpoint in this function.
  752. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  753. if (CLI.NumResultRegs)
  754. updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
  755. return true;
  756. }
  757. bool FastISel::selectXRayCustomEvent(const CallInst *I) {
  758. const auto &Triple = TM.getTargetTriple();
  759. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  760. return true; // don't do anything to this instruction.
  761. SmallVector<MachineOperand, 8> Ops;
  762. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
  763. /*IsDef=*/false));
  764. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
  765. /*IsDef=*/false));
  766. MachineInstrBuilder MIB =
  767. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  768. TII.get(TargetOpcode::PATCHABLE_EVENT_CALL));
  769. for (auto &MO : Ops)
  770. MIB.add(MO);
  771. // Insert the Patchable Event Call instruction, that gets lowered properly.
  772. return true;
  773. }
  774. /// Returns an AttributeList representing the attributes applied to the return
  775. /// value of the given call.
  776. static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
  777. SmallVector<Attribute::AttrKind, 2> Attrs;
  778. if (CLI.RetSExt)
  779. Attrs.push_back(Attribute::SExt);
  780. if (CLI.RetZExt)
  781. Attrs.push_back(Attribute::ZExt);
  782. if (CLI.IsInReg)
  783. Attrs.push_back(Attribute::InReg);
  784. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  785. Attrs);
  786. }
  787. bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
  788. unsigned NumArgs) {
  789. MCContext &Ctx = MF->getContext();
  790. SmallString<32> MangledName;
  791. Mangler::getNameWithPrefix(MangledName, SymName, DL);
  792. MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
  793. return lowerCallTo(CI, Sym, NumArgs);
  794. }
  795. bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol,
  796. unsigned NumArgs) {
  797. ImmutableCallSite CS(CI);
  798. FunctionType *FTy = CS.getFunctionType();
  799. Type *RetTy = CS.getType();
  800. ArgListTy Args;
  801. Args.reserve(NumArgs);
  802. // Populate the argument list.
  803. // Attributes for args start at offset 1, after the return attribute.
  804. for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
  805. Value *V = CI->getOperand(ArgI);
  806. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  807. ArgListEntry Entry;
  808. Entry.Val = V;
  809. Entry.Ty = V->getType();
  810. Entry.setAttributes(&CS, ArgI);
  811. Args.push_back(Entry);
  812. }
  813. TLI.markLibCallAttributes(MF, CS.getCallingConv(), Args);
  814. CallLoweringInfo CLI;
  815. CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), CS, NumArgs);
  816. return lowerCallTo(CLI);
  817. }
  818. bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
  819. // Handle the incoming return values from the call.
  820. CLI.clearIns();
  821. SmallVector<EVT, 4> RetTys;
  822. ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys);
  823. SmallVector<ISD::OutputArg, 4> Outs;
  824. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL);
  825. bool CanLowerReturn = TLI.CanLowerReturn(
  826. CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  827. // FIXME: sret demotion isn't supported yet - bail out.
  828. if (!CanLowerReturn)
  829. return false;
  830. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  831. EVT VT = RetTys[I];
  832. MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
  833. unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
  834. for (unsigned i = 0; i != NumRegs; ++i) {
  835. ISD::InputArg MyFlags;
  836. MyFlags.VT = RegisterVT;
  837. MyFlags.ArgVT = VT;
  838. MyFlags.Used = CLI.IsReturnValueUsed;
  839. if (CLI.RetSExt)
  840. MyFlags.Flags.setSExt();
  841. if (CLI.RetZExt)
  842. MyFlags.Flags.setZExt();
  843. if (CLI.IsInReg)
  844. MyFlags.Flags.setInReg();
  845. CLI.Ins.push_back(MyFlags);
  846. }
  847. }
  848. // Handle all of the outgoing arguments.
  849. CLI.clearOuts();
  850. for (auto &Arg : CLI.getArgs()) {
  851. Type *FinalType = Arg.Ty;
  852. if (Arg.IsByVal)
  853. FinalType = cast<PointerType>(Arg.Ty)->getElementType();
  854. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  855. FinalType, CLI.CallConv, CLI.IsVarArg);
  856. ISD::ArgFlagsTy Flags;
  857. if (Arg.IsZExt)
  858. Flags.setZExt();
  859. if (Arg.IsSExt)
  860. Flags.setSExt();
  861. if (Arg.IsInReg)
  862. Flags.setInReg();
  863. if (Arg.IsSRet)
  864. Flags.setSRet();
  865. if (Arg.IsSwiftSelf)
  866. Flags.setSwiftSelf();
  867. if (Arg.IsSwiftError)
  868. Flags.setSwiftError();
  869. if (Arg.IsByVal)
  870. Flags.setByVal();
  871. if (Arg.IsInAlloca) {
  872. Flags.setInAlloca();
  873. // Set the byval flag for CCAssignFn callbacks that don't know about
  874. // inalloca. This way we can know how many bytes we should've allocated
  875. // and how many bytes a callee cleanup function will pop. If we port
  876. // inalloca to more targets, we'll have to add custom inalloca handling in
  877. // the various CC lowering callbacks.
  878. Flags.setByVal();
  879. }
  880. if (Arg.IsByVal || Arg.IsInAlloca) {
  881. PointerType *Ty = cast<PointerType>(Arg.Ty);
  882. Type *ElementTy = Ty->getElementType();
  883. unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
  884. // For ByVal, alignment should come from FE. BE will guess if this info is
  885. // not there, but there are cases it cannot get right.
  886. unsigned FrameAlign = Arg.Alignment;
  887. if (!FrameAlign)
  888. FrameAlign = TLI.getByValTypeAlignment(ElementTy, DL);
  889. Flags.setByValSize(FrameSize);
  890. Flags.setByValAlign(FrameAlign);
  891. }
  892. if (Arg.IsNest)
  893. Flags.setNest();
  894. if (NeedsRegBlock)
  895. Flags.setInConsecutiveRegs();
  896. unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty);
  897. Flags.setOrigAlign(OriginalAlignment);
  898. CLI.OutVals.push_back(Arg.Val);
  899. CLI.OutFlags.push_back(Flags);
  900. }
  901. if (!fastLowerCall(CLI))
  902. return false;
  903. // Set all unused physreg defs as dead.
  904. assert(CLI.Call && "No call instruction specified.");
  905. CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
  906. if (CLI.NumResultRegs && CLI.CS)
  907. updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
  908. return true;
  909. }
  910. bool FastISel::lowerCall(const CallInst *CI) {
  911. ImmutableCallSite CS(CI);
  912. FunctionType *FuncTy = CS.getFunctionType();
  913. Type *RetTy = CS.getType();
  914. ArgListTy Args;
  915. ArgListEntry Entry;
  916. Args.reserve(CS.arg_size());
  917. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  918. i != e; ++i) {
  919. Value *V = *i;
  920. // Skip empty types
  921. if (V->getType()->isEmptyTy())
  922. continue;
  923. Entry.Val = V;
  924. Entry.Ty = V->getType();
  925. // Skip the first return-type Attribute to get to params.
  926. Entry.setAttributes(&CS, i - CS.arg_begin());
  927. Args.push_back(Entry);
  928. }
  929. // Check if target-independent constraints permit a tail call here.
  930. // Target-dependent constraints are checked within fastLowerCall.
  931. bool IsTailCall = CI->isTailCall();
  932. if (IsTailCall && !isInTailCallPosition(CS, TM))
  933. IsTailCall = false;
  934. CallLoweringInfo CLI;
  935. CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS)
  936. .setTailCall(IsTailCall);
  937. return lowerCallTo(CLI);
  938. }
  939. bool FastISel::selectCall(const User *I) {
  940. const CallInst *Call = cast<CallInst>(I);
  941. // Handle simple inline asms.
  942. if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
  943. // If the inline asm has side effects, then make sure that no local value
  944. // lives across by flushing the local value map.
  945. if (IA->hasSideEffects())
  946. flushLocalValueMap();
  947. // Don't attempt to handle constraints.
  948. if (!IA->getConstraintString().empty())
  949. return false;
  950. unsigned ExtraInfo = 0;
  951. if (IA->hasSideEffects())
  952. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  953. if (IA->isAlignStack())
  954. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  955. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  956. TII.get(TargetOpcode::INLINEASM))
  957. .addExternalSymbol(IA->getAsmString().c_str())
  958. .addImm(ExtraInfo);
  959. return true;
  960. }
  961. MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
  962. computeUsesVAFloatArgument(*Call, MMI);
  963. // Handle intrinsic function calls.
  964. if (const auto *II = dyn_cast<IntrinsicInst>(Call))
  965. return selectIntrinsicCall(II);
  966. // Usually, it does not make sense to initialize a value,
  967. // make an unrelated function call and use the value, because
  968. // it tends to be spilled on the stack. So, we move the pointer
  969. // to the last local value to the beginning of the block, so that
  970. // all the values which have already been materialized,
  971. // appear after the call. It also makes sense to skip intrinsics
  972. // since they tend to be inlined.
  973. flushLocalValueMap();
  974. return lowerCall(Call);
  975. }
  976. bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
  977. switch (II->getIntrinsicID()) {
  978. default:
  979. break;
  980. // At -O0 we don't care about the lifetime intrinsics.
  981. case Intrinsic::lifetime_start:
  982. case Intrinsic::lifetime_end:
  983. // The donothing intrinsic does, well, nothing.
  984. case Intrinsic::donothing:
  985. // Neither does the sideeffect intrinsic.
  986. case Intrinsic::sideeffect:
  987. // Neither does the assume intrinsic; it's also OK not to codegen its operand.
  988. case Intrinsic::assume:
  989. return true;
  990. case Intrinsic::dbg_declare: {
  991. const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
  992. assert(DI->getVariable() && "Missing variable");
  993. if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
  994. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  995. return true;
  996. }
  997. const Value *Address = DI->getAddress();
  998. if (!Address || isa<UndefValue>(Address)) {
  999. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1000. return true;
  1001. }
  1002. // Byval arguments with frame indices were already handled after argument
  1003. // lowering and before isel.
  1004. const auto *Arg =
  1005. dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
  1006. if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
  1007. return true;
  1008. Optional<MachineOperand> Op;
  1009. if (unsigned Reg = lookUpRegForValue(Address))
  1010. Op = MachineOperand::CreateReg(Reg, false);
  1011. // If we have a VLA that has a "use" in a metadata node that's then used
  1012. // here but it has no other uses, then we have a problem. E.g.,
  1013. //
  1014. // int foo (const int *x) {
  1015. // char a[*x];
  1016. // return 0;
  1017. // }
  1018. //
  1019. // If we assign 'a' a vreg and fast isel later on has to use the selection
  1020. // DAG isel, it will want to copy the value to the vreg. However, there are
  1021. // no uses, which goes counter to what selection DAG isel expects.
  1022. if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
  1023. (!isa<AllocaInst>(Address) ||
  1024. !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
  1025. Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
  1026. false);
  1027. if (Op) {
  1028. assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
  1029. "Expected inlined-at fields to agree");
  1030. if (Op->isReg()) {
  1031. Op->setIsDebug(true);
  1032. // A dbg.declare describes the address of a source variable, so lower it
  1033. // into an indirect DBG_VALUE.
  1034. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1035. TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true,
  1036. Op->getReg(), DI->getVariable(), DI->getExpression());
  1037. } else
  1038. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1039. TII.get(TargetOpcode::DBG_VALUE))
  1040. .add(*Op)
  1041. .addImm(0)
  1042. .addMetadata(DI->getVariable())
  1043. .addMetadata(DI->getExpression());
  1044. } else {
  1045. // We can't yet handle anything else here because it would require
  1046. // generating code, thus altering codegen because of debug info.
  1047. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1048. }
  1049. return true;
  1050. }
  1051. case Intrinsic::dbg_value: {
  1052. // This form of DBG_VALUE is target-independent.
  1053. const DbgValueInst *DI = cast<DbgValueInst>(II);
  1054. const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
  1055. const Value *V = DI->getValue();
  1056. assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
  1057. "Expected inlined-at fields to agree");
  1058. if (!V) {
  1059. // Currently the optimizer can produce this; insert an undef to
  1060. // help debugging. Probably the optimizer should not do this.
  1061. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U,
  1062. DI->getVariable(), DI->getExpression());
  1063. } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
  1064. if (CI->getBitWidth() > 64)
  1065. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1066. .addCImm(CI)
  1067. .addImm(0U)
  1068. .addMetadata(DI->getVariable())
  1069. .addMetadata(DI->getExpression());
  1070. else
  1071. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1072. .addImm(CI->getZExtValue())
  1073. .addImm(0U)
  1074. .addMetadata(DI->getVariable())
  1075. .addMetadata(DI->getExpression());
  1076. } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
  1077. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1078. .addFPImm(CF)
  1079. .addImm(0U)
  1080. .addMetadata(DI->getVariable())
  1081. .addMetadata(DI->getExpression());
  1082. } else if (unsigned Reg = lookUpRegForValue(V)) {
  1083. // FIXME: This does not handle register-indirect values at offset 0.
  1084. bool IsIndirect = false;
  1085. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
  1086. DI->getVariable(), DI->getExpression());
  1087. } else {
  1088. // We can't yet handle anything else here because it would require
  1089. // generating code, thus altering codegen because of debug info.
  1090. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1091. }
  1092. return true;
  1093. }
  1094. case Intrinsic::objectsize: {
  1095. ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
  1096. unsigned long long Res = CI->isZero() ? -1ULL : 0;
  1097. Constant *ResCI = ConstantInt::get(II->getType(), Res);
  1098. unsigned ResultReg = getRegForValue(ResCI);
  1099. if (!ResultReg)
  1100. return false;
  1101. updateValueMap(II, ResultReg);
  1102. return true;
  1103. }
  1104. case Intrinsic::invariant_group_barrier:
  1105. case Intrinsic::expect: {
  1106. unsigned ResultReg = getRegForValue(II->getArgOperand(0));
  1107. if (!ResultReg)
  1108. return false;
  1109. updateValueMap(II, ResultReg);
  1110. return true;
  1111. }
  1112. case Intrinsic::experimental_stackmap:
  1113. return selectStackmap(II);
  1114. case Intrinsic::experimental_patchpoint_void:
  1115. case Intrinsic::experimental_patchpoint_i64:
  1116. return selectPatchpoint(II);
  1117. case Intrinsic::xray_customevent:
  1118. return selectXRayCustomEvent(II);
  1119. }
  1120. return fastLowerIntrinsicCall(II);
  1121. }
  1122. bool FastISel::selectCast(const User *I, unsigned Opcode) {
  1123. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1124. EVT DstVT = TLI.getValueType(DL, I->getType());
  1125. if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
  1126. !DstVT.isSimple())
  1127. // Unhandled type. Halt "fast" selection and bail.
  1128. return false;
  1129. // Check if the destination type is legal.
  1130. if (!TLI.isTypeLegal(DstVT))
  1131. return false;
  1132. // Check if the source operand is legal.
  1133. if (!TLI.isTypeLegal(SrcVT))
  1134. return false;
  1135. unsigned InputReg = getRegForValue(I->getOperand(0));
  1136. if (!InputReg)
  1137. // Unhandled operand. Halt "fast" selection and bail.
  1138. return false;
  1139. bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
  1140. unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
  1141. Opcode, InputReg, InputRegIsKill);
  1142. if (!ResultReg)
  1143. return false;
  1144. updateValueMap(I, ResultReg);
  1145. return true;
  1146. }
  1147. bool FastISel::selectBitCast(const User *I) {
  1148. // If the bitcast doesn't change the type, just use the operand value.
  1149. if (I->getType() == I->getOperand(0)->getType()) {
  1150. unsigned Reg = getRegForValue(I->getOperand(0));
  1151. if (!Reg)
  1152. return false;
  1153. updateValueMap(I, Reg);
  1154. return true;
  1155. }
  1156. // Bitcasts of other values become reg-reg copies or BITCAST operators.
  1157. EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1158. EVT DstEVT = TLI.getValueType(DL, I->getType());
  1159. if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
  1160. !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
  1161. // Unhandled type. Halt "fast" selection and bail.
  1162. return false;
  1163. MVT SrcVT = SrcEVT.getSimpleVT();
  1164. MVT DstVT = DstEVT.getSimpleVT();
  1165. unsigned Op0 = getRegForValue(I->getOperand(0));
  1166. if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
  1167. return false;
  1168. bool Op0IsKill = hasTrivialKill(I->getOperand(0));
  1169. // First, try to perform the bitcast by inserting a reg-reg copy.
  1170. unsigned ResultReg = 0;
  1171. if (SrcVT == DstVT) {
  1172. const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
  1173. const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
  1174. // Don't attempt a cross-class copy. It will likely fail.
  1175. if (SrcClass == DstClass) {
  1176. ResultReg = createResultReg(DstClass);
  1177. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1178. TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
  1179. }
  1180. }
  1181. // If the reg-reg copy failed, select a BITCAST opcode.
  1182. if (!ResultReg)
  1183. ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
  1184. if (!ResultReg)
  1185. return false;
  1186. updateValueMap(I, ResultReg);
  1187. return true;
  1188. }
  1189. // Remove local value instructions starting from the instruction after
  1190. // SavedLastLocalValue to the current function insert point.
  1191. void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
  1192. {
  1193. MachineInstr *CurLastLocalValue = getLastLocalValue();
  1194. if (CurLastLocalValue != SavedLastLocalValue) {
  1195. // Find the first local value instruction to be deleted.
  1196. // This is the instruction after SavedLastLocalValue if it is non-NULL.
  1197. // Otherwise it's the first instruction in the block.
  1198. MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
  1199. if (SavedLastLocalValue)
  1200. ++FirstDeadInst;
  1201. else
  1202. FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
  1203. setLastLocalValue(SavedLastLocalValue);
  1204. removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
  1205. }
  1206. }
  1207. bool FastISel::selectInstruction(const Instruction *I) {
  1208. MachineInstr *SavedLastLocalValue = getLastLocalValue();
  1209. // Just before the terminator instruction, insert instructions to
  1210. // feed PHI nodes in successor blocks.
  1211. if (isa<TerminatorInst>(I)) {
  1212. if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
  1213. // PHI node handling may have generated local value instructions,
  1214. // even though it failed to handle all PHI nodes.
  1215. // We remove these instructions because SelectionDAGISel will generate
  1216. // them again.
  1217. removeDeadLocalValueCode(SavedLastLocalValue);
  1218. return false;
  1219. }
  1220. }
  1221. // FastISel does not handle any operand bundles except OB_funclet.
  1222. if (ImmutableCallSite CS = ImmutableCallSite(I))
  1223. for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i)
  1224. if (CS.getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet)
  1225. return false;
  1226. DbgLoc = I->getDebugLoc();
  1227. SavedInsertPt = FuncInfo.InsertPt;
  1228. if (const auto *Call = dyn_cast<CallInst>(I)) {
  1229. const Function *F = Call->getCalledFunction();
  1230. LibFunc Func;
  1231. // As a special case, don't handle calls to builtin library functions that
  1232. // may be translated directly to target instructions.
  1233. if (F && !F->hasLocalLinkage() && F->hasName() &&
  1234. LibInfo->getLibFunc(F->getName(), Func) &&
  1235. LibInfo->hasOptimizedCodeGen(Func))
  1236. return false;
  1237. // Don't handle Intrinsic::trap if a trap function is specified.
  1238. if (F && F->getIntrinsicID() == Intrinsic::trap &&
  1239. Call->hasFnAttr("trap-func-name"))
  1240. return false;
  1241. }
  1242. // First, try doing target-independent selection.
  1243. if (!SkipTargetIndependentISel) {
  1244. if (selectOperator(I, I->getOpcode())) {
  1245. ++NumFastIselSuccessIndependent;
  1246. DbgLoc = DebugLoc();
  1247. return true;
  1248. }
  1249. // Remove dead code.
  1250. recomputeInsertPt();
  1251. if (SavedInsertPt != FuncInfo.InsertPt)
  1252. removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
  1253. SavedInsertPt = FuncInfo.InsertPt;
  1254. }
  1255. // Next, try calling the target to attempt to handle the instruction.
  1256. if (fastSelectInstruction(I)) {
  1257. ++NumFastIselSuccessTarget;
  1258. DbgLoc = DebugLoc();
  1259. return true;
  1260. }
  1261. // Remove dead code.
  1262. recomputeInsertPt();
  1263. if (SavedInsertPt != FuncInfo.InsertPt)
  1264. removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
  1265. DbgLoc = DebugLoc();
  1266. // Undo phi node updates, because they will be added again by SelectionDAG.
  1267. if (isa<TerminatorInst>(I)) {
  1268. // PHI node handling may have generated local value instructions.
  1269. // We remove them because SelectionDAGISel will generate them again.
  1270. removeDeadLocalValueCode(SavedLastLocalValue);
  1271. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  1272. }
  1273. return false;
  1274. }
  1275. /// Emit an unconditional branch to the given block, unless it is the immediate
  1276. /// (fall-through) successor, and update the CFG.
  1277. void FastISel::fastEmitBranch(MachineBasicBlock *MSucc,
  1278. const DebugLoc &DbgLoc) {
  1279. if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
  1280. FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
  1281. // For more accurate line information if this is the only instruction
  1282. // in the block then emit it, otherwise we have the unconditional
  1283. // fall-through case, which needs no instructions.
  1284. } else {
  1285. // The unconditional branch case.
  1286. TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr,
  1287. SmallVector<MachineOperand, 0>(), DbgLoc);
  1288. }
  1289. if (FuncInfo.BPI) {
  1290. auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
  1291. FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
  1292. FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
  1293. } else
  1294. FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
  1295. }
  1296. void FastISel::finishCondBranch(const BasicBlock *BranchBB,
  1297. MachineBasicBlock *TrueMBB,
  1298. MachineBasicBlock *FalseMBB) {
  1299. // Add TrueMBB as successor unless it is equal to the FalseMBB: This can
  1300. // happen in degenerate IR and MachineIR forbids to have a block twice in the
  1301. // successor/predecessor lists.
  1302. if (TrueMBB != FalseMBB) {
  1303. if (FuncInfo.BPI) {
  1304. auto BranchProbability =
  1305. FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
  1306. FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
  1307. } else
  1308. FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
  1309. }
  1310. fastEmitBranch(FalseMBB, DbgLoc);
  1311. }
  1312. /// Emit an FNeg operation.
  1313. bool FastISel::selectFNeg(const User *I) {
  1314. unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
  1315. if (!OpReg)
  1316. return false;
  1317. bool OpRegIsKill = hasTrivialKill(I);
  1318. // If the target has ISD::FNEG, use it.
  1319. EVT VT = TLI.getValueType(DL, I->getType());
  1320. unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
  1321. OpReg, OpRegIsKill);
  1322. if (ResultReg) {
  1323. updateValueMap(I, ResultReg);
  1324. return true;
  1325. }
  1326. // Bitcast the value to integer, twiddle the sign bit with xor,
  1327. // and then bitcast it back to floating-point.
  1328. if (VT.getSizeInBits() > 64)
  1329. return false;
  1330. EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
  1331. if (!TLI.isTypeLegal(IntVT))
  1332. return false;
  1333. unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
  1334. ISD::BITCAST, OpReg, OpRegIsKill);
  1335. if (!IntReg)
  1336. return false;
  1337. unsigned IntResultReg = fastEmit_ri_(
  1338. IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true,
  1339. UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
  1340. if (!IntResultReg)
  1341. return false;
  1342. ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
  1343. IntResultReg, /*IsKill=*/true);
  1344. if (!ResultReg)
  1345. return false;
  1346. updateValueMap(I, ResultReg);
  1347. return true;
  1348. }
  1349. bool FastISel::selectExtractValue(const User *U) {
  1350. const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
  1351. if (!EVI)
  1352. return false;
  1353. // Make sure we only try to handle extracts with a legal result. But also
  1354. // allow i1 because it's easy.
  1355. EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
  1356. if (!RealVT.isSimple())
  1357. return false;
  1358. MVT VT = RealVT.getSimpleVT();
  1359. if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
  1360. return false;
  1361. const Value *Op0 = EVI->getOperand(0);
  1362. Type *AggTy = Op0->getType();
  1363. // Get the base result register.
  1364. unsigned ResultReg;
  1365. DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
  1366. if (I != FuncInfo.ValueMap.end())
  1367. ResultReg = I->second;
  1368. else if (isa<Instruction>(Op0))
  1369. ResultReg = FuncInfo.InitializeRegForValue(Op0);
  1370. else
  1371. return false; // fast-isel can't handle aggregate constants at the moment
  1372. // Get the actual result register, which is an offset from the base register.
  1373. unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
  1374. SmallVector<EVT, 4> AggValueVTs;
  1375. ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
  1376. for (unsigned i = 0; i < VTIndex; i++)
  1377. ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
  1378. updateValueMap(EVI, ResultReg);
  1379. return true;
  1380. }
  1381. bool FastISel::selectOperator(const User *I, unsigned Opcode) {
  1382. switch (Opcode) {
  1383. case Instruction::Add:
  1384. return selectBinaryOp(I, ISD::ADD);
  1385. case Instruction::FAdd:
  1386. return selectBinaryOp(I, ISD::FADD);
  1387. case Instruction::Sub:
  1388. return selectBinaryOp(I, ISD::SUB);
  1389. case Instruction::FSub:
  1390. // FNeg is currently represented in LLVM IR as a special case of FSub.
  1391. if (BinaryOperator::isFNeg(I))
  1392. return selectFNeg(I);
  1393. return selectBinaryOp(I, ISD::FSUB);
  1394. case Instruction::Mul:
  1395. return selectBinaryOp(I, ISD::MUL);
  1396. case Instruction::FMul:
  1397. return selectBinaryOp(I, ISD::FMUL);
  1398. case Instruction::SDiv:
  1399. return selectBinaryOp(I, ISD::SDIV);
  1400. case Instruction::UDiv:
  1401. return selectBinaryOp(I, ISD::UDIV);
  1402. case Instruction::FDiv:
  1403. return selectBinaryOp(I, ISD::FDIV);
  1404. case Instruction::SRem:
  1405. return selectBinaryOp(I, ISD::SREM);
  1406. case Instruction::URem:
  1407. return selectBinaryOp(I, ISD::UREM);
  1408. case Instruction::FRem:
  1409. return selectBinaryOp(I, ISD::FREM);
  1410. case Instruction::Shl:
  1411. return selectBinaryOp(I, ISD::SHL);
  1412. case Instruction::LShr:
  1413. return selectBinaryOp(I, ISD::SRL);
  1414. case Instruction::AShr:
  1415. return selectBinaryOp(I, ISD::SRA);
  1416. case Instruction::And:
  1417. return selectBinaryOp(I, ISD::AND);
  1418. case Instruction::Or:
  1419. return selectBinaryOp(I, ISD::OR);
  1420. case Instruction::Xor:
  1421. return selectBinaryOp(I, ISD::XOR);
  1422. case Instruction::GetElementPtr:
  1423. return selectGetElementPtr(I);
  1424. case Instruction::Br: {
  1425. const BranchInst *BI = cast<BranchInst>(I);
  1426. if (BI->isUnconditional()) {
  1427. const BasicBlock *LLVMSucc = BI->getSuccessor(0);
  1428. MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
  1429. fastEmitBranch(MSucc, BI->getDebugLoc());
  1430. return true;
  1431. }
  1432. // Conditional branches are not handed yet.
  1433. // Halt "fast" selection and bail.
  1434. return false;
  1435. }
  1436. case Instruction::Unreachable:
  1437. if (TM.Options.TrapUnreachable)
  1438. return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
  1439. else
  1440. return true;
  1441. case Instruction::Alloca:
  1442. // FunctionLowering has the static-sized case covered.
  1443. if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
  1444. return true;
  1445. // Dynamic-sized alloca is not handled yet.
  1446. return false;
  1447. case Instruction::Call:
  1448. return selectCall(I);
  1449. case Instruction::BitCast:
  1450. return selectBitCast(I);
  1451. case Instruction::FPToSI:
  1452. return selectCast(I, ISD::FP_TO_SINT);
  1453. case Instruction::ZExt:
  1454. return selectCast(I, ISD::ZERO_EXTEND);
  1455. case Instruction::SExt:
  1456. return selectCast(I, ISD::SIGN_EXTEND);
  1457. case Instruction::Trunc:
  1458. return selectCast(I, ISD::TRUNCATE);
  1459. case Instruction::SIToFP:
  1460. return selectCast(I, ISD::SINT_TO_FP);
  1461. case Instruction::IntToPtr: // Deliberate fall-through.
  1462. case Instruction::PtrToInt: {
  1463. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1464. EVT DstVT = TLI.getValueType(DL, I->getType());
  1465. if (DstVT.bitsGT(SrcVT))
  1466. return selectCast(I, ISD::ZERO_EXTEND);
  1467. if (DstVT.bitsLT(SrcVT))
  1468. return selectCast(I, ISD::TRUNCATE);
  1469. unsigned Reg = getRegForValue(I->getOperand(0));
  1470. if (!Reg)
  1471. return false;
  1472. updateValueMap(I, Reg);
  1473. return true;
  1474. }
  1475. case Instruction::ExtractValue:
  1476. return selectExtractValue(I);
  1477. case Instruction::PHI:
  1478. llvm_unreachable("FastISel shouldn't visit PHI nodes!");
  1479. default:
  1480. // Unhandled instruction. Halt "fast" selection and bail.
  1481. return false;
  1482. }
  1483. }
  1484. FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
  1485. const TargetLibraryInfo *LibInfo,
  1486. bool SkipTargetIndependentISel)
  1487. : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
  1488. MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
  1489. TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
  1490. TII(*MF->getSubtarget().getInstrInfo()),
  1491. TLI(*MF->getSubtarget().getTargetLowering()),
  1492. TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
  1493. SkipTargetIndependentISel(SkipTargetIndependentISel) {}
  1494. FastISel::~FastISel() = default;
  1495. bool FastISel::fastLowerArguments() { return false; }
  1496. bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
  1497. bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
  1498. return false;
  1499. }
  1500. unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
  1501. unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
  1502. bool /*Op0IsKill*/) {
  1503. return 0;
  1504. }
  1505. unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
  1506. bool /*Op0IsKill*/, unsigned /*Op1*/,
  1507. bool /*Op1IsKill*/) {
  1508. return 0;
  1509. }
  1510. unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
  1511. return 0;
  1512. }
  1513. unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
  1514. const ConstantFP * /*FPImm*/) {
  1515. return 0;
  1516. }
  1517. unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
  1518. bool /*Op0IsKill*/, uint64_t /*Imm*/) {
  1519. return 0;
  1520. }
  1521. /// This method is a wrapper of fastEmit_ri. It first tries to emit an
  1522. /// instruction with an immediate operand using fastEmit_ri.
  1523. /// If that fails, it materializes the immediate into a register and try
  1524. /// fastEmit_rr instead.
  1525. unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
  1526. bool Op0IsKill, uint64_t Imm, MVT ImmType) {
  1527. // If this is a multiply by a power of two, emit this as a shift left.
  1528. if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
  1529. Opcode = ISD::SHL;
  1530. Imm = Log2_64(Imm);
  1531. } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
  1532. // div x, 8 -> srl x, 3
  1533. Opcode = ISD::SRL;
  1534. Imm = Log2_64(Imm);
  1535. }
  1536. // Horrible hack (to be removed), check to make sure shift amounts are
  1537. // in-range.
  1538. if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
  1539. Imm >= VT.getSizeInBits())
  1540. return 0;
  1541. // First check if immediate type is legal. If not, we can't use the ri form.
  1542. unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
  1543. if (ResultReg)
  1544. return ResultReg;
  1545. unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
  1546. bool IsImmKill = true;
  1547. if (!MaterialReg) {
  1548. // This is a bit ugly/slow, but failing here means falling out of
  1549. // fast-isel, which would be very slow.
  1550. IntegerType *ITy =
  1551. IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
  1552. MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
  1553. if (!MaterialReg)
  1554. return 0;
  1555. // FIXME: If the materialized register here has no uses yet then this
  1556. // will be the first use and we should be able to mark it as killed.
  1557. // However, the local value area for materialising constant expressions
  1558. // grows down, not up, which means that any constant expressions we generate
  1559. // later which also use 'Imm' could be after this instruction and therefore
  1560. // after this kill.
  1561. IsImmKill = false;
  1562. }
  1563. return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill);
  1564. }
  1565. unsigned FastISel::createResultReg(const TargetRegisterClass *RC) {
  1566. return MRI.createVirtualRegister(RC);
  1567. }
  1568. unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
  1569. unsigned OpNum) {
  1570. if (TargetRegisterInfo::isVirtualRegister(Op)) {
  1571. const TargetRegisterClass *RegClass =
  1572. TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
  1573. if (!MRI.constrainRegClass(Op, RegClass)) {
  1574. // If it's not legal to COPY between the register classes, something
  1575. // has gone very wrong before we got here.
  1576. unsigned NewOp = createResultReg(RegClass);
  1577. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1578. TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
  1579. return NewOp;
  1580. }
  1581. }
  1582. return Op;
  1583. }
  1584. unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode,
  1585. const TargetRegisterClass *RC) {
  1586. unsigned ResultReg = createResultReg(RC);
  1587. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1588. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
  1589. return ResultReg;
  1590. }
  1591. unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
  1592. const TargetRegisterClass *RC, unsigned Op0,
  1593. bool Op0IsKill) {
  1594. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1595. unsigned ResultReg = createResultReg(RC);
  1596. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1597. if (II.getNumDefs() >= 1)
  1598. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1599. .addReg(Op0, getKillRegState(Op0IsKill));
  1600. else {
  1601. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1602. .addReg(Op0, getKillRegState(Op0IsKill));
  1603. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1604. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1605. }
  1606. return ResultReg;
  1607. }
  1608. unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
  1609. const TargetRegisterClass *RC, unsigned Op0,
  1610. bool Op0IsKill, unsigned Op1,
  1611. bool Op1IsKill) {
  1612. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1613. unsigned ResultReg = createResultReg(RC);
  1614. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1615. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1616. if (II.getNumDefs() >= 1)
  1617. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1618. .addReg(Op0, getKillRegState(Op0IsKill))
  1619. .addReg(Op1, getKillRegState(Op1IsKill));
  1620. else {
  1621. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1622. .addReg(Op0, getKillRegState(Op0IsKill))
  1623. .addReg(Op1, getKillRegState(Op1IsKill));
  1624. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1625. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1626. }
  1627. return ResultReg;
  1628. }
  1629. unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
  1630. const TargetRegisterClass *RC, unsigned Op0,
  1631. bool Op0IsKill, unsigned Op1,
  1632. bool Op1IsKill, unsigned Op2,
  1633. bool Op2IsKill) {
  1634. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1635. unsigned ResultReg = createResultReg(RC);
  1636. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1637. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1638. Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
  1639. if (II.getNumDefs() >= 1)
  1640. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1641. .addReg(Op0, getKillRegState(Op0IsKill))
  1642. .addReg(Op1, getKillRegState(Op1IsKill))
  1643. .addReg(Op2, getKillRegState(Op2IsKill));
  1644. else {
  1645. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1646. .addReg(Op0, getKillRegState(Op0IsKill))
  1647. .addReg(Op1, getKillRegState(Op1IsKill))
  1648. .addReg(Op2, getKillRegState(Op2IsKill));
  1649. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1650. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1651. }
  1652. return ResultReg;
  1653. }
  1654. unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
  1655. const TargetRegisterClass *RC, unsigned Op0,
  1656. bool Op0IsKill, uint64_t Imm) {
  1657. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1658. unsigned ResultReg = createResultReg(RC);
  1659. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1660. if (II.getNumDefs() >= 1)
  1661. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1662. .addReg(Op0, getKillRegState(Op0IsKill))
  1663. .addImm(Imm);
  1664. else {
  1665. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1666. .addReg(Op0, getKillRegState(Op0IsKill))
  1667. .addImm(Imm);
  1668. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1669. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1670. }
  1671. return ResultReg;
  1672. }
  1673. unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
  1674. const TargetRegisterClass *RC, unsigned Op0,
  1675. bool Op0IsKill, uint64_t Imm1,
  1676. uint64_t Imm2) {
  1677. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1678. unsigned ResultReg = createResultReg(RC);
  1679. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1680. if (II.getNumDefs() >= 1)
  1681. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1682. .addReg(Op0, getKillRegState(Op0IsKill))
  1683. .addImm(Imm1)
  1684. .addImm(Imm2);
  1685. else {
  1686. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1687. .addReg(Op0, getKillRegState(Op0IsKill))
  1688. .addImm(Imm1)
  1689. .addImm(Imm2);
  1690. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1691. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1692. }
  1693. return ResultReg;
  1694. }
  1695. unsigned FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
  1696. const TargetRegisterClass *RC,
  1697. const ConstantFP *FPImm) {
  1698. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1699. unsigned ResultReg = createResultReg(RC);
  1700. if (II.getNumDefs() >= 1)
  1701. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1702. .addFPImm(FPImm);
  1703. else {
  1704. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1705. .addFPImm(FPImm);
  1706. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1707. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1708. }
  1709. return ResultReg;
  1710. }
  1711. unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
  1712. const TargetRegisterClass *RC, unsigned Op0,
  1713. bool Op0IsKill, unsigned Op1,
  1714. bool Op1IsKill, uint64_t Imm) {
  1715. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1716. unsigned ResultReg = createResultReg(RC);
  1717. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1718. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1719. if (II.getNumDefs() >= 1)
  1720. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1721. .addReg(Op0, getKillRegState(Op0IsKill))
  1722. .addReg(Op1, getKillRegState(Op1IsKill))
  1723. .addImm(Imm);
  1724. else {
  1725. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1726. .addReg(Op0, getKillRegState(Op0IsKill))
  1727. .addReg(Op1, getKillRegState(Op1IsKill))
  1728. .addImm(Imm);
  1729. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1730. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1731. }
  1732. return ResultReg;
  1733. }
  1734. unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
  1735. const TargetRegisterClass *RC, uint64_t Imm) {
  1736. unsigned ResultReg = createResultReg(RC);
  1737. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1738. if (II.getNumDefs() >= 1)
  1739. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1740. .addImm(Imm);
  1741. else {
  1742. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
  1743. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1744. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1745. }
  1746. return ResultReg;
  1747. }
  1748. unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
  1749. bool Op0IsKill, uint32_t Idx) {
  1750. unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
  1751. assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
  1752. "Cannot yet extract from physregs");
  1753. const TargetRegisterClass *RC = MRI.getRegClass(Op0);
  1754. MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
  1755. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
  1756. ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
  1757. return ResultReg;
  1758. }
  1759. /// Emit MachineInstrs to compute the value of Op with all but the least
  1760. /// significant bit set to zero.
  1761. unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
  1762. return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
  1763. }
  1764. /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
  1765. /// Emit code to ensure constants are copied into registers when needed.
  1766. /// Remember the virtual registers that need to be added to the Machine PHI
  1767. /// nodes as input. We cannot just directly add them, because expansion
  1768. /// might result in multiple MBB's for one BB. As such, the start of the
  1769. /// BB might correspond to a different MBB than the end.
  1770. bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  1771. const TerminatorInst *TI = LLVMBB->getTerminator();
  1772. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  1773. FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
  1774. // Check successor nodes' PHI nodes that expect a constant to be available
  1775. // from this block.
  1776. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  1777. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  1778. if (!isa<PHINode>(SuccBB->begin()))
  1779. continue;
  1780. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  1781. // If this terminator has multiple identical successors (common for
  1782. // switches), only handle each succ once.
  1783. if (!SuccsHandled.insert(SuccMBB).second)
  1784. continue;
  1785. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  1786. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  1787. // nodes and Machine PHI nodes, but the incoming operands have not been
  1788. // emitted yet.
  1789. for (const PHINode &PN : SuccBB->phis()) {
  1790. // Ignore dead phi's.
  1791. if (PN.use_empty())
  1792. continue;
  1793. // Only handle legal types. Two interesting things to note here. First,
  1794. // by bailing out early, we may leave behind some dead instructions,
  1795. // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
  1796. // own moves. Second, this check is necessary because FastISel doesn't
  1797. // use CreateRegs to create registers, so it always creates
  1798. // exactly one register for each non-void instruction.
  1799. EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true);
  1800. if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
  1801. // Handle integer promotions, though, because they're common and easy.
  1802. if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
  1803. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  1804. return false;
  1805. }
  1806. }
  1807. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  1808. // Set the DebugLoc for the copy. Prefer the location of the operand
  1809. // if there is one; use the location of the PHI otherwise.
  1810. DbgLoc = PN.getDebugLoc();
  1811. if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
  1812. DbgLoc = Inst->getDebugLoc();
  1813. unsigned Reg = getRegForValue(PHIOp);
  1814. if (!Reg) {
  1815. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  1816. return false;
  1817. }
  1818. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg));
  1819. DbgLoc = DebugLoc();
  1820. }
  1821. }
  1822. return true;
  1823. }
  1824. bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
  1825. assert(LI->hasOneUse() &&
  1826. "tryToFoldLoad expected a LoadInst with a single use");
  1827. // We know that the load has a single use, but don't know what it is. If it
  1828. // isn't one of the folded instructions, then we can't succeed here. Handle
  1829. // this by scanning the single-use users of the load until we get to FoldInst.
  1830. unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
  1831. const Instruction *TheUser = LI->user_back();
  1832. while (TheUser != FoldInst && // Scan up until we find FoldInst.
  1833. // Stay in the right block.
  1834. TheUser->getParent() == FoldInst->getParent() &&
  1835. --MaxUsers) { // Don't scan too far.
  1836. // If there are multiple or no uses of this instruction, then bail out.
  1837. if (!TheUser->hasOneUse())
  1838. return false;
  1839. TheUser = TheUser->user_back();
  1840. }
  1841. // If we didn't find the fold instruction, then we failed to collapse the
  1842. // sequence.
  1843. if (TheUser != FoldInst)
  1844. return false;
  1845. // Don't try to fold volatile loads. Target has to deal with alignment
  1846. // constraints.
  1847. if (LI->isVolatile())
  1848. return false;
  1849. // Figure out which vreg this is going into. If there is no assigned vreg yet
  1850. // then there actually was no reference to it. Perhaps the load is referenced
  1851. // by a dead instruction.
  1852. unsigned LoadReg = getRegForValue(LI);
  1853. if (!LoadReg)
  1854. return false;
  1855. // We can't fold if this vreg has no uses or more than one use. Multiple uses
  1856. // may mean that the instruction got lowered to multiple MIs, or the use of
  1857. // the loaded value ended up being multiple operands of the result.
  1858. if (!MRI.hasOneUse(LoadReg))
  1859. return false;
  1860. MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
  1861. MachineInstr *User = RI->getParent();
  1862. // Set the insertion point properly. Folding the load can cause generation of
  1863. // other random instructions (like sign extends) for addressing modes; make
  1864. // sure they get inserted in a logical place before the new instruction.
  1865. FuncInfo.InsertPt = User;
  1866. FuncInfo.MBB = User->getParent();
  1867. // Ask the target to try folding the load.
  1868. return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
  1869. }
  1870. bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
  1871. // Must be an add.
  1872. if (!isa<AddOperator>(Add))
  1873. return false;
  1874. // Type size needs to match.
  1875. if (DL.getTypeSizeInBits(GEP->getType()) !=
  1876. DL.getTypeSizeInBits(Add->getType()))
  1877. return false;
  1878. // Must be in the same basic block.
  1879. if (isa<Instruction>(Add) &&
  1880. FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
  1881. return false;
  1882. // Must have a constant operand.
  1883. return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
  1884. }
  1885. MachineMemOperand *
  1886. FastISel::createMachineMemOperandFor(const Instruction *I) const {
  1887. const Value *Ptr;
  1888. Type *ValTy;
  1889. unsigned Alignment;
  1890. MachineMemOperand::Flags Flags;
  1891. bool IsVolatile;
  1892. if (const auto *LI = dyn_cast<LoadInst>(I)) {
  1893. Alignment = LI->getAlignment();
  1894. IsVolatile = LI->isVolatile();
  1895. Flags = MachineMemOperand::MOLoad;
  1896. Ptr = LI->getPointerOperand();
  1897. ValTy = LI->getType();
  1898. } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
  1899. Alignment = SI->getAlignment();
  1900. IsVolatile = SI->isVolatile();
  1901. Flags = MachineMemOperand::MOStore;
  1902. Ptr = SI->getPointerOperand();
  1903. ValTy = SI->getValueOperand()->getType();
  1904. } else
  1905. return nullptr;
  1906. bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  1907. bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  1908. bool IsDereferenceable =
  1909. I->getMetadata(LLVMContext::MD_dereferenceable) != nullptr;
  1910. const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
  1911. AAMDNodes AAInfo;
  1912. I->getAAMetadata(AAInfo);
  1913. if (Alignment == 0) // Ensure that codegen never sees alignment 0.
  1914. Alignment = DL.getABITypeAlignment(ValTy);
  1915. unsigned Size = DL.getTypeStoreSize(ValTy);
  1916. if (IsVolatile)
  1917. Flags |= MachineMemOperand::MOVolatile;
  1918. if (IsNonTemporal)
  1919. Flags |= MachineMemOperand::MONonTemporal;
  1920. if (IsDereferenceable)
  1921. Flags |= MachineMemOperand::MODereferenceable;
  1922. if (IsInvariant)
  1923. Flags |= MachineMemOperand::MOInvariant;
  1924. return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
  1925. Alignment, AAInfo, Ranges);
  1926. }
  1927. CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
  1928. // If both operands are the same, then try to optimize or fold the cmp.
  1929. CmpInst::Predicate Predicate = CI->getPredicate();
  1930. if (CI->getOperand(0) != CI->getOperand(1))
  1931. return Predicate;
  1932. switch (Predicate) {
  1933. default: llvm_unreachable("Invalid predicate!");
  1934. case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
  1935. case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
  1936. case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
  1937. case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
  1938. case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
  1939. case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
  1940. case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
  1941. case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
  1942. case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
  1943. case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
  1944. case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
  1945. case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
  1946. case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
  1947. case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
  1948. case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
  1949. case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
  1950. case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
  1951. case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
  1952. case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
  1953. case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
  1954. case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
  1955. case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
  1956. case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
  1957. case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
  1958. case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
  1959. case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
  1960. }
  1961. return Predicate;
  1962. }