FunctionLoweringInfo.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
  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 implements routines for translating functions from LLVM IR into
  11. // Machine IR.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "function-lowering-info"
  15. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  16. #include "llvm/ADT/PostOrderIterator.h"
  17. #include "llvm/CodeGen/Analysis.h"
  18. #include "llvm/CodeGen/MachineFrameInfo.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineInstrBuilder.h"
  21. #include "llvm/CodeGen/MachineModuleInfo.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/DataLayout.h"
  24. #include "llvm/DebugInfo.h"
  25. #include "llvm/DerivedTypes.h"
  26. #include "llvm/Function.h"
  27. #include "llvm/Instructions.h"
  28. #include "llvm/IntrinsicInst.h"
  29. #include "llvm/LLVMContext.h"
  30. #include "llvm/Module.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/MathExtras.h"
  34. #include "llvm/Target/TargetInstrInfo.h"
  35. #include "llvm/Target/TargetLowering.h"
  36. #include "llvm/Target/TargetOptions.h"
  37. #include "llvm/Target/TargetRegisterInfo.h"
  38. #include <algorithm>
  39. using namespace llvm;
  40. /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
  41. /// PHI nodes or outside of the basic block that defines it, or used by a
  42. /// switch or atomic instruction, which may expand to multiple basic blocks.
  43. static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
  44. if (I->use_empty()) return false;
  45. if (isa<PHINode>(I)) return true;
  46. const BasicBlock *BB = I->getParent();
  47. for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end();
  48. UI != E; ++UI) {
  49. const User *U = *UI;
  50. if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
  51. return true;
  52. }
  53. return false;
  54. }
  55. FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
  56. : TLI(tli) {
  57. }
  58. void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
  59. Fn = &fn;
  60. MF = &mf;
  61. RegInfo = &MF->getRegInfo();
  62. // Check whether the function can return without sret-demotion.
  63. SmallVector<ISD::OutputArg, 4> Outs;
  64. GetReturnInfo(Fn->getReturnType(),
  65. Fn->getAttributes().getRetAttributes(), Outs, TLI);
  66. CanLowerReturn = TLI.CanLowerReturn(Fn->getCallingConv(), *MF,
  67. Fn->isVarArg(),
  68. Outs, Fn->getContext());
  69. // Initialize the mapping of values to registers. This is only set up for
  70. // instruction values that are used outside of the block that defines
  71. // them.
  72. Function::const_iterator BB = Fn->begin(), EB = Fn->end();
  73. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  74. if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
  75. if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
  76. Type *Ty = AI->getAllocatedType();
  77. uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
  78. unsigned Align =
  79. std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
  80. AI->getAlignment());
  81. TySize *= CUI->getZExtValue(); // Get total allocated size.
  82. if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
  83. // The object may need to be placed onto the stack near the stack
  84. // protector if one exists. Determine here if this object is a suitable
  85. // candidate. I.e., it would trigger the creation of a stack protector.
  86. bool MayNeedSP =
  87. (AI->isArrayAllocation() ||
  88. (TySize >= 8 && isa<ArrayType>(Ty) &&
  89. cast<ArrayType>(Ty)->getElementType()->isIntegerTy(8)));
  90. StaticAllocaMap[AI] =
  91. MF->getFrameInfo()->CreateStackObject(TySize, Align, false,
  92. MayNeedSP, AI);
  93. }
  94. for (; BB != EB; ++BB)
  95. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  96. I != E; ++I) {
  97. // Mark values used outside their block as exported, by allocating
  98. // a virtual register for them.
  99. if (isUsedOutsideOfDefiningBlock(I))
  100. if (!isa<AllocaInst>(I) ||
  101. !StaticAllocaMap.count(cast<AllocaInst>(I)))
  102. InitializeRegForValue(I);
  103. // Collect llvm.dbg.declare information. This is done now instead of
  104. // during the initial isel pass through the IR so that it is done
  105. // in a predictable order.
  106. if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
  107. MachineModuleInfo &MMI = MF->getMMI();
  108. if (MMI.hasDebugInfo() &&
  109. DIVariable(DI->getVariable()).Verify() &&
  110. !DI->getDebugLoc().isUnknown()) {
  111. // Don't handle byval struct arguments or VLAs, for example.
  112. // Non-byval arguments are handled here (they refer to the stack
  113. // temporary alloca at this point).
  114. const Value *Address = DI->getAddress();
  115. if (Address) {
  116. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  117. Address = BCI->getOperand(0);
  118. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
  119. DenseMap<const AllocaInst *, int>::iterator SI =
  120. StaticAllocaMap.find(AI);
  121. if (SI != StaticAllocaMap.end()) { // Check for VLAs.
  122. int FI = SI->second;
  123. MMI.setVariableDbgInfo(DI->getVariable(),
  124. FI, DI->getDebugLoc());
  125. }
  126. }
  127. }
  128. }
  129. }
  130. }
  131. // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
  132. // also creates the initial PHI MachineInstrs, though none of the input
  133. // operands are populated.
  134. for (BB = Fn->begin(); BB != EB; ++BB) {
  135. MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
  136. MBBMap[BB] = MBB;
  137. MF->push_back(MBB);
  138. // Transfer the address-taken flag. This is necessary because there could
  139. // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
  140. // the first one should be marked.
  141. if (BB->hasAddressTaken())
  142. MBB->setHasAddressTaken();
  143. // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
  144. // appropriate.
  145. for (BasicBlock::const_iterator I = BB->begin();
  146. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  147. if (PN->use_empty()) continue;
  148. // Skip empty types
  149. if (PN->getType()->isEmptyTy())
  150. continue;
  151. DebugLoc DL = PN->getDebugLoc();
  152. unsigned PHIReg = ValueMap[PN];
  153. assert(PHIReg && "PHI node does not have an assigned virtual register!");
  154. SmallVector<EVT, 4> ValueVTs;
  155. ComputeValueVTs(TLI, PN->getType(), ValueVTs);
  156. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  157. EVT VT = ValueVTs[vti];
  158. unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
  159. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  160. for (unsigned i = 0; i != NumRegisters; ++i)
  161. BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
  162. PHIReg += NumRegisters;
  163. }
  164. }
  165. }
  166. // Mark landing pad blocks.
  167. for (BB = Fn->begin(); BB != EB; ++BB)
  168. if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
  169. MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
  170. }
  171. /// clear - Clear out all the function-specific state. This returns this
  172. /// FunctionLoweringInfo to an empty state, ready to be used for a
  173. /// different function.
  174. void FunctionLoweringInfo::clear() {
  175. assert(CatchInfoFound.size() == CatchInfoLost.size() &&
  176. "Not all catch info was assigned to a landing pad!");
  177. MBBMap.clear();
  178. ValueMap.clear();
  179. StaticAllocaMap.clear();
  180. #ifndef NDEBUG
  181. CatchInfoLost.clear();
  182. CatchInfoFound.clear();
  183. #endif
  184. LiveOutRegInfo.clear();
  185. VisitedBBs.clear();
  186. ArgDbgValues.clear();
  187. ByValArgFrameIndexMap.clear();
  188. RegFixups.clear();
  189. }
  190. /// CreateReg - Allocate a single virtual register for the given type.
  191. unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
  192. return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
  193. }
  194. /// CreateRegs - Allocate the appropriate number of virtual registers of
  195. /// the correctly promoted or expanded types. Assign these registers
  196. /// consecutive vreg numbers and return the first assigned number.
  197. ///
  198. /// In the case that the given value has struct or array type, this function
  199. /// will assign registers for each member or element.
  200. ///
  201. unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
  202. SmallVector<EVT, 4> ValueVTs;
  203. ComputeValueVTs(TLI, Ty, ValueVTs);
  204. unsigned FirstReg = 0;
  205. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  206. EVT ValueVT = ValueVTs[Value];
  207. MVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT).getSimpleVT();
  208. unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
  209. for (unsigned i = 0; i != NumRegs; ++i) {
  210. unsigned R = CreateReg(RegisterVT);
  211. if (!FirstReg) FirstReg = R;
  212. }
  213. }
  214. return FirstReg;
  215. }
  216. /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
  217. /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
  218. /// the register's LiveOutInfo is for a smaller bit width, it is extended to
  219. /// the larger bit width by zero extension. The bit width must be no smaller
  220. /// than the LiveOutInfo's existing bit width.
  221. const FunctionLoweringInfo::LiveOutInfo *
  222. FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
  223. if (!LiveOutRegInfo.inBounds(Reg))
  224. return NULL;
  225. LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
  226. if (!LOI->IsValid)
  227. return NULL;
  228. if (BitWidth > LOI->KnownZero.getBitWidth()) {
  229. LOI->NumSignBits = 1;
  230. LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
  231. LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
  232. }
  233. return LOI;
  234. }
  235. /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
  236. /// register based on the LiveOutInfo of its operands.
  237. void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
  238. Type *Ty = PN->getType();
  239. if (!Ty->isIntegerTy() || Ty->isVectorTy())
  240. return;
  241. SmallVector<EVT, 1> ValueVTs;
  242. ComputeValueVTs(TLI, Ty, ValueVTs);
  243. assert(ValueVTs.size() == 1 &&
  244. "PHIs with non-vector integer types should have a single VT.");
  245. EVT IntVT = ValueVTs[0];
  246. if (TLI.getNumRegisters(PN->getContext(), IntVT) != 1)
  247. return;
  248. IntVT = TLI.getTypeToTransformTo(PN->getContext(), IntVT);
  249. unsigned BitWidth = IntVT.getSizeInBits();
  250. unsigned DestReg = ValueMap[PN];
  251. if (!TargetRegisterInfo::isVirtualRegister(DestReg))
  252. return;
  253. LiveOutRegInfo.grow(DestReg);
  254. LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
  255. Value *V = PN->getIncomingValue(0);
  256. if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
  257. DestLOI.NumSignBits = 1;
  258. APInt Zero(BitWidth, 0);
  259. DestLOI.KnownZero = Zero;
  260. DestLOI.KnownOne = Zero;
  261. return;
  262. }
  263. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  264. APInt Val = CI->getValue().zextOrTrunc(BitWidth);
  265. DestLOI.NumSignBits = Val.getNumSignBits();
  266. DestLOI.KnownZero = ~Val;
  267. DestLOI.KnownOne = Val;
  268. } else {
  269. assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
  270. "CopyToReg node was created.");
  271. unsigned SrcReg = ValueMap[V];
  272. if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
  273. DestLOI.IsValid = false;
  274. return;
  275. }
  276. const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
  277. if (!SrcLOI) {
  278. DestLOI.IsValid = false;
  279. return;
  280. }
  281. DestLOI = *SrcLOI;
  282. }
  283. assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
  284. DestLOI.KnownOne.getBitWidth() == BitWidth &&
  285. "Masks should have the same bit width as the type.");
  286. for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
  287. Value *V = PN->getIncomingValue(i);
  288. if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
  289. DestLOI.NumSignBits = 1;
  290. APInt Zero(BitWidth, 0);
  291. DestLOI.KnownZero = Zero;
  292. DestLOI.KnownOne = Zero;
  293. return;
  294. }
  295. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  296. APInt Val = CI->getValue().zextOrTrunc(BitWidth);
  297. DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
  298. DestLOI.KnownZero &= ~Val;
  299. DestLOI.KnownOne &= Val;
  300. continue;
  301. }
  302. assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
  303. "its CopyToReg node was created.");
  304. unsigned SrcReg = ValueMap[V];
  305. if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
  306. DestLOI.IsValid = false;
  307. return;
  308. }
  309. const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
  310. if (!SrcLOI) {
  311. DestLOI.IsValid = false;
  312. return;
  313. }
  314. DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
  315. DestLOI.KnownZero &= SrcLOI->KnownZero;
  316. DestLOI.KnownOne &= SrcLOI->KnownOne;
  317. }
  318. }
  319. /// setArgumentFrameIndex - Record frame index for the byval
  320. /// argument. This overrides previous frame index entry for this argument,
  321. /// if any.
  322. void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
  323. int FI) {
  324. ByValArgFrameIndexMap[A] = FI;
  325. }
  326. /// getArgumentFrameIndex - Get frame index for the byval argument.
  327. /// If the argument does not have any assigned frame index then 0 is
  328. /// returned.
  329. int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
  330. DenseMap<const Argument *, int>::iterator I =
  331. ByValArgFrameIndexMap.find(A);
  332. if (I != ByValArgFrameIndexMap.end())
  333. return I->second;
  334. DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
  335. return 0;
  336. }
  337. /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
  338. /// being passed to this variadic function, and set the MachineModuleInfo's
  339. /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
  340. /// reference to _fltused on Windows, which will link in MSVCRT's
  341. /// floating-point support.
  342. void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
  343. MachineModuleInfo *MMI)
  344. {
  345. FunctionType *FT = cast<FunctionType>(
  346. I.getCalledValue()->getType()->getContainedType(0));
  347. if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
  348. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  349. Type* T = I.getArgOperand(i)->getType();
  350. for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
  351. i != e; ++i) {
  352. if (i->isFloatingPointTy()) {
  353. MMI->setUsesVAFloatArgument(true);
  354. return;
  355. }
  356. }
  357. }
  358. }
  359. }
  360. /// AddCatchInfo - Extract the personality and type infos from an eh.selector
  361. /// call, and add them to the specified machine basic block.
  362. void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
  363. MachineBasicBlock *MBB) {
  364. // Inform the MachineModuleInfo of the personality for this landing pad.
  365. const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
  366. assert(CE->getOpcode() == Instruction::BitCast &&
  367. isa<Function>(CE->getOperand(0)) &&
  368. "Personality should be a function");
  369. MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
  370. // Gather all the type infos for this landing pad and pass them along to
  371. // MachineModuleInfo.
  372. std::vector<const GlobalVariable *> TyInfo;
  373. unsigned N = I.getNumArgOperands();
  374. for (unsigned i = N - 1; i > 1; --i) {
  375. if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
  376. unsigned FilterLength = CI->getZExtValue();
  377. unsigned FirstCatch = i + FilterLength + !FilterLength;
  378. assert(FirstCatch <= N && "Invalid filter length");
  379. if (FirstCatch < N) {
  380. TyInfo.reserve(N - FirstCatch);
  381. for (unsigned j = FirstCatch; j < N; ++j)
  382. TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
  383. MMI->addCatchTypeInfo(MBB, TyInfo);
  384. TyInfo.clear();
  385. }
  386. if (!FilterLength) {
  387. // Cleanup.
  388. MMI->addCleanup(MBB);
  389. } else {
  390. // Filter.
  391. TyInfo.reserve(FilterLength - 1);
  392. for (unsigned j = i + 1; j < FirstCatch; ++j)
  393. TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
  394. MMI->addFilterTypeInfo(MBB, TyInfo);
  395. TyInfo.clear();
  396. }
  397. N = i;
  398. }
  399. }
  400. if (N > 2) {
  401. TyInfo.reserve(N - 2);
  402. for (unsigned j = 2; j < N; ++j)
  403. TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
  404. MMI->addCatchTypeInfo(MBB, TyInfo);
  405. }
  406. }
  407. /// AddLandingPadInfo - Extract the exception handling information from the
  408. /// landingpad instruction and add them to the specified machine module info.
  409. void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
  410. MachineBasicBlock *MBB) {
  411. MMI.addPersonality(MBB,
  412. cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
  413. if (I.isCleanup())
  414. MMI.addCleanup(MBB);
  415. // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
  416. // but we need to do it this way because of how the DWARF EH emitter
  417. // processes the clauses.
  418. for (unsigned i = I.getNumClauses(); i != 0; --i) {
  419. Value *Val = I.getClause(i - 1);
  420. if (I.isCatch(i - 1)) {
  421. MMI.addCatchTypeInfo(MBB,
  422. dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
  423. } else {
  424. // Add filters in a list.
  425. Constant *CVal = cast<Constant>(Val);
  426. SmallVector<const GlobalVariable*, 4> FilterList;
  427. for (User::op_iterator
  428. II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
  429. FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
  430. MMI.addFilterTypeInfo(MBB, FilterList);
  431. }
  432. }
  433. }