1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating functions from LLVM IR into
13 //===----------------------------------------------------------------------===//
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/CodeGen/WinEHFuncInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "function-lowering-info"
47 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
48 /// PHI nodes or outside of the basic block that defines it, or used by a
49 /// switch or atomic instruction, which may expand to multiple basic blocks.
50 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
51 if (I->use_empty()) return false;
52 if (isa<PHINode>(I)) return true;
53 const BasicBlock *BB = I->getParent();
54 for (const User *U : I->users())
55 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
61 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
62 // For the users of the source value being used for compare instruction, if
63 // the number of signed predicate is greater than unsigned predicate, we
64 // prefer to use SIGN_EXTEND.
66 // With this optimization, we would be able to reduce some redundant sign or
67 // zero extension instruction, and eventually more machine CSE opportunities
69 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
70 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
71 for (const User *U : V->users()) {
72 if (const auto *CI = dyn_cast<CmpInst>(U)) {
73 NumOfSigned += CI->isSigned();
74 NumOfUnsigned += CI->isUnsigned();
77 if (NumOfSigned > NumOfUnsigned)
78 ExtendKind = ISD::SIGN_EXTEND;
83 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
87 TLI = MF->getSubtarget().getTargetLowering();
88 RegInfo = &MF->getRegInfo();
89 MachineModuleInfo &MMI = MF->getMMI();
91 // Check whether the function can return without sret-demotion.
92 SmallVector<ISD::OutputArg, 4> Outs;
93 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
95 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
96 Fn->isVarArg(), Outs, Fn->getContext());
98 // Initialize the mapping of values to registers. This is only set up for
99 // instruction values that are used outside of the block that defines
101 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
102 for (; BB != EB; ++BB)
103 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
105 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
106 // Static allocas can be folded into the initial stack frame adjustment.
107 if (AI->isStaticAlloca()) {
108 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
109 Type *Ty = AI->getAllocatedType();
110 uint64_t TySize = MF->getDataLayout().getTypeAllocSize(Ty);
112 std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(Ty),
115 TySize *= CUI->getZExtValue(); // Get total allocated size.
116 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
118 StaticAllocaMap[AI] =
119 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
123 std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(
124 AI->getAllocatedType()),
126 unsigned StackAlign =
127 MF->getSubtarget().getFrameLowering()->getStackAlignment();
128 if (Align <= StackAlign)
130 // Inform the Frame Information that we have variable-sized objects.
131 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
135 // Look for inline asm that clobbers the SP register.
136 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
137 ImmutableCallSite CS(I);
138 if (isa<InlineAsm>(CS.getCalledValue())) {
139 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
140 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
141 std::vector<TargetLowering::AsmOperandInfo> Ops =
142 TLI->ParseConstraints(Fn->getParent()->getDataLayout(), TRI, CS);
143 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
144 TargetLowering::AsmOperandInfo &Op = Ops[I];
145 if (Op.Type == InlineAsm::isClobber) {
146 // Clobbers don't have SDValue operands, hence SDValue().
147 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
148 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
149 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
151 if (PhysReg.first == SP)
152 MF->getFrameInfo()->setHasOpaqueSPAdjustment(true);
158 // Look for calls to the @llvm.va_start intrinsic. We can omit some
159 // prologue boilerplate for variadic functions that don't examine their
161 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
162 if (II->getIntrinsicID() == Intrinsic::vastart)
163 MF->getFrameInfo()->setHasVAStart(true);
166 // If we have a musttail call in a variadic funciton, we need to ensure we
167 // forward implicit register parameters.
168 if (const auto *CI = dyn_cast<CallInst>(I)) {
169 if (CI->isMustTailCall() && Fn->isVarArg())
170 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
173 // Mark values used outside their block as exported, by allocating
174 // a virtual register for them.
175 if (isUsedOutsideOfDefiningBlock(I))
176 if (!isa<AllocaInst>(I) ||
177 !StaticAllocaMap.count(cast<AllocaInst>(I)))
178 InitializeRegForValue(I);
180 // Collect llvm.dbg.declare information. This is done now instead of
181 // during the initial isel pass through the IR so that it is done
182 // in a predictable order.
183 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
184 assert(DI->getVariable() && "Missing variable");
185 assert(DI->getDebugLoc() && "Missing location");
186 if (MMI.hasDebugInfo()) {
187 // Don't handle byval struct arguments or VLAs, for example.
188 // Non-byval arguments are handled here (they refer to the stack
189 // temporary alloca at this point).
190 const Value *Address = DI->getAddress();
192 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
193 Address = BCI->getOperand(0);
194 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
195 DenseMap<const AllocaInst *, int>::iterator SI =
196 StaticAllocaMap.find(AI);
197 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
199 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
200 FI, DI->getDebugLoc());
207 // Decide the preferred extend type for a value.
208 PreferredExtendType[I] = getPreferredExtendForValue(I);
211 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
212 // also creates the initial PHI MachineInstrs, though none of the input
213 // operands are populated.
214 for (BB = Fn->begin(); BB != EB; ++BB) {
215 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
219 // Transfer the address-taken flag. This is necessary because there could
220 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
221 // the first one should be marked.
222 if (BB->hasAddressTaken())
223 MBB->setHasAddressTaken();
225 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
227 for (BasicBlock::const_iterator I = BB->begin();
228 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
229 if (PN->use_empty()) continue;
232 if (PN->getType()->isEmptyTy())
235 DebugLoc DL = PN->getDebugLoc();
236 unsigned PHIReg = ValueMap[PN];
237 assert(PHIReg && "PHI node does not have an assigned virtual register!");
239 SmallVector<EVT, 4> ValueVTs;
240 ComputeValueVTs(*TLI, MF->getDataLayout(), PN->getType(), ValueVTs);
241 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
242 EVT VT = ValueVTs[vti];
243 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
244 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
245 for (unsigned i = 0; i != NumRegisters; ++i)
246 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
247 PHIReg += NumRegisters;
252 // Mark landing pad blocks.
253 SmallVector<const LandingPadInst *, 4> LPads;
254 for (BB = Fn->begin(); BB != EB; ++BB) {
255 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
256 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
257 if (BB->isLandingPad())
258 LPads.push_back(BB->getLandingPadInst());
261 // If this is an MSVC EH personality, we need to do a bit more work.
262 EHPersonality Personality = EHPersonality::Unknown;
263 if (Fn->hasPersonalityFn())
264 Personality = classifyEHPersonality(Fn->getPersonalityFn());
265 if (!isMSVCEHPersonality(Personality))
268 if (Personality == EHPersonality::MSVC_Win64SEH ||
269 Personality == EHPersonality::MSVC_X86SEH) {
270 addSEHHandlersForLPads(LPads);
273 WinEHFuncInfo &EHInfo = MMI.getWinEHFuncInfo(&fn);
274 if (Personality == EHPersonality::MSVC_CXX) {
275 const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
276 calculateWinCXXEHStateNumbers(WinEHParentFn, EHInfo);
279 // Copy the state numbers to LandingPadInfo for the current function, which
280 // could be a handler or the parent. This should happen for 32-bit SEH and
282 if (Personality == EHPersonality::MSVC_CXX ||
283 Personality == EHPersonality::MSVC_X86SEH) {
284 for (const LandingPadInst *LP : LPads) {
285 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
286 MMI.addWinEHState(LPadMBB, EHInfo.LandingPadStateMap[LP]);
291 void FunctionLoweringInfo::addSEHHandlersForLPads(
292 ArrayRef<const LandingPadInst *> LPads) {
293 MachineModuleInfo &MMI = MF->getMMI();
295 // Iterate over all landing pads with llvm.eh.actions calls.
296 for (const LandingPadInst *LP : LPads) {
297 const IntrinsicInst *ActionsCall =
298 dyn_cast<IntrinsicInst>(LP->getNextNode());
300 ActionsCall->getIntrinsicID() != Intrinsic::eh_actions)
303 // Parse the llvm.eh.actions call we found.
304 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
305 SmallVector<std::unique_ptr<ActionHandler>, 4> Actions;
306 parseEHActions(ActionsCall, Actions);
308 // Iterate EH actions from most to least precedence, which means
309 // iterating in reverse.
310 for (auto I = Actions.rbegin(), E = Actions.rend(); I != E; ++I) {
311 ActionHandler *Action = I->get();
312 if (auto *CH = dyn_cast<CatchHandler>(Action)) {
314 dyn_cast<Function>(CH->getSelector()->stripPointerCasts());
315 assert((Filter || CH->getSelector()->isNullValue()) &&
316 "expected function or catch-all");
317 const auto *RecoverBA =
318 cast<BlockAddress>(CH->getHandlerBlockOrFunc());
319 MMI.addSEHCatchHandler(LPadMBB, Filter, RecoverBA);
321 assert(isa<CleanupHandler>(Action));
322 const auto *Fini = cast<Function>(Action->getHandlerBlockOrFunc());
323 MMI.addSEHCleanupHandler(LPadMBB, Fini);
329 /// clear - Clear out all the function-specific state. This returns this
330 /// FunctionLoweringInfo to an empty state, ready to be used for a
331 /// different function.
332 void FunctionLoweringInfo::clear() {
333 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
334 "Not all catch info was assigned to a landing pad!");
338 StaticAllocaMap.clear();
340 CatchInfoLost.clear();
341 CatchInfoFound.clear();
343 LiveOutRegInfo.clear();
345 ArgDbgValues.clear();
346 ByValArgFrameIndexMap.clear();
348 StatepointStackSlots.clear();
349 StatepointRelocatedValues.clear();
350 PreferredExtendType.clear();
353 /// CreateReg - Allocate a single virtual register for the given type.
354 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
355 return RegInfo->createVirtualRegister(
356 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
359 /// CreateRegs - Allocate the appropriate number of virtual registers of
360 /// the correctly promoted or expanded types. Assign these registers
361 /// consecutive vreg numbers and return the first assigned number.
363 /// In the case that the given value has struct or array type, this function
364 /// will assign registers for each member or element.
366 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
367 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
369 SmallVector<EVT, 4> ValueVTs;
370 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
372 unsigned FirstReg = 0;
373 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
374 EVT ValueVT = ValueVTs[Value];
375 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
377 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
378 for (unsigned i = 0; i != NumRegs; ++i) {
379 unsigned R = CreateReg(RegisterVT);
380 if (!FirstReg) FirstReg = R;
386 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
387 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
388 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
389 /// the larger bit width by zero extension. The bit width must be no smaller
390 /// than the LiveOutInfo's existing bit width.
391 const FunctionLoweringInfo::LiveOutInfo *
392 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
393 if (!LiveOutRegInfo.inBounds(Reg))
396 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
400 if (BitWidth > LOI->KnownZero.getBitWidth()) {
401 LOI->NumSignBits = 1;
402 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
403 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
409 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
410 /// register based on the LiveOutInfo of its operands.
411 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
412 Type *Ty = PN->getType();
413 if (!Ty->isIntegerTy() || Ty->isVectorTy())
416 SmallVector<EVT, 1> ValueVTs;
417 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
418 assert(ValueVTs.size() == 1 &&
419 "PHIs with non-vector integer types should have a single VT.");
420 EVT IntVT = ValueVTs[0];
422 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
424 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
425 unsigned BitWidth = IntVT.getSizeInBits();
427 unsigned DestReg = ValueMap[PN];
428 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
430 LiveOutRegInfo.grow(DestReg);
431 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
433 Value *V = PN->getIncomingValue(0);
434 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
435 DestLOI.NumSignBits = 1;
436 APInt Zero(BitWidth, 0);
437 DestLOI.KnownZero = Zero;
438 DestLOI.KnownOne = Zero;
442 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
443 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
444 DestLOI.NumSignBits = Val.getNumSignBits();
445 DestLOI.KnownZero = ~Val;
446 DestLOI.KnownOne = Val;
448 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
449 "CopyToReg node was created.");
450 unsigned SrcReg = ValueMap[V];
451 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
452 DestLOI.IsValid = false;
455 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
457 DestLOI.IsValid = false;
463 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
464 DestLOI.KnownOne.getBitWidth() == BitWidth &&
465 "Masks should have the same bit width as the type.");
467 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
468 Value *V = PN->getIncomingValue(i);
469 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
470 DestLOI.NumSignBits = 1;
471 APInt Zero(BitWidth, 0);
472 DestLOI.KnownZero = Zero;
473 DestLOI.KnownOne = Zero;
477 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
478 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
479 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
480 DestLOI.KnownZero &= ~Val;
481 DestLOI.KnownOne &= Val;
485 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
486 "its CopyToReg node was created.");
487 unsigned SrcReg = ValueMap[V];
488 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
489 DestLOI.IsValid = false;
492 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
494 DestLOI.IsValid = false;
497 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
498 DestLOI.KnownZero &= SrcLOI->KnownZero;
499 DestLOI.KnownOne &= SrcLOI->KnownOne;
503 /// setArgumentFrameIndex - Record frame index for the byval
504 /// argument. This overrides previous frame index entry for this argument,
506 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
508 ByValArgFrameIndexMap[A] = FI;
511 /// getArgumentFrameIndex - Get frame index for the byval argument.
512 /// If the argument does not have any assigned frame index then 0 is
514 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
515 DenseMap<const Argument *, int>::iterator I =
516 ByValArgFrameIndexMap.find(A);
517 if (I != ByValArgFrameIndexMap.end())
519 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
523 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
524 /// being passed to this variadic function, and set the MachineModuleInfo's
525 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
526 /// reference to _fltused on Windows, which will link in MSVCRT's
527 /// floating-point support.
528 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
529 MachineModuleInfo *MMI)
531 FunctionType *FT = cast<FunctionType>(
532 I.getCalledValue()->getType()->getContainedType(0));
533 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
534 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
535 Type* T = I.getArgOperand(i)->getType();
536 for (auto i : post_order(T)) {
537 if (i->isFloatingPointTy()) {
538 MMI->setUsesVAFloatArgument(true);
546 /// AddLandingPadInfo - Extract the exception handling information from the
547 /// landingpad instruction and add them to the specified machine module info.
548 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
549 MachineBasicBlock *MBB) {
553 I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts()));
558 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
559 // but we need to do it this way because of how the DWARF EH emitter
560 // processes the clauses.
561 for (unsigned i = I.getNumClauses(); i != 0; --i) {
562 Value *Val = I.getClause(i - 1);
563 if (I.isCatch(i - 1)) {
564 MMI.addCatchTypeInfo(MBB,
565 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
567 // Add filters in a list.
568 Constant *CVal = cast<Constant>(Val);
569 SmallVector<const GlobalValue*, 4> FilterList;
570 for (User::op_iterator
571 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
572 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
574 MMI.addFilterTypeInfo(MBB, FilterList);