FastISel.cpp 82 KB

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