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/CodeGen/Analysis.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/WinEHFuncInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetFrameLowering.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
44 #define DEBUG_TYPE "function-lowering-info"
46 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
47 /// PHI nodes or outside of the basic block that defines it, or used by a
48 /// switch or atomic instruction, which may expand to multiple basic blocks.
49 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
50 if (I->use_empty()) return false;
51 if (isa<PHINode>(I)) return true;
52 const BasicBlock *BB = I->getParent();
53 for (const User *U : I->users())
54 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
60 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
61 // For the users of the source value being used for compare instruction, if
62 // the number of signed predicate is greater than unsigned predicate, we
63 // prefer to use SIGN_EXTEND.
65 // With this optimization, we would be able to reduce some redundant sign or
66 // zero extension instruction, and eventually more machine CSE opportunities
68 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
69 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
70 for (const User *U : V->users()) {
71 if (const auto *CI = dyn_cast<CmpInst>(U)) {
72 NumOfSigned += CI->isSigned();
73 NumOfUnsigned += CI->isUnsigned();
76 if (NumOfSigned > NumOfUnsigned)
77 ExtendKind = ISD::SIGN_EXTEND;
82 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
86 TLI = MF->getSubtarget().getTargetLowering();
87 RegInfo = &MF->getRegInfo();
88 MachineModuleInfo &MMI = MF->getMMI();
89 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
90 unsigned StackAlign = TFI->getStackAlignment();
92 // Check whether the function can return without sret-demotion.
93 SmallVector<ISD::OutputArg, 4> Outs;
94 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
96 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
97 Fn->isVarArg(), Outs, Fn->getContext());
99 // If this personality uses funclets, we need to do a bit more work.
100 DenseMap<const AllocaInst *, TinyPtrVector<int *>> CatchObjects;
101 EHPersonality Personality = classifyEHPersonality(
102 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr);
103 if (isFuncletEHPersonality(Personality)) {
104 // Calculate state numbers if we haven't already.
105 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
106 if (Personality == EHPersonality::MSVC_CXX)
107 calculateWinCXXEHStateNumbers(&fn, EHInfo);
108 else if (isAsynchronousEHPersonality(Personality))
109 calculateSEHStateNumbers(&fn, EHInfo);
110 else if (Personality == EHPersonality::CoreCLR)
111 calculateClrEHStateNumbers(&fn, EHInfo);
113 // Map all BB references in the WinEH data to MBBs.
114 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
115 for (WinEHHandlerType &H : TBME.HandlerArray) {
116 if (const AllocaInst *AI = H.CatchObj.Alloca)
117 CatchObjects.insert({AI, {}}).first->second.push_back(
118 &H.CatchObj.FrameIndex);
120 H.CatchObj.FrameIndex = INT_MAX;
125 // Initialize the mapping of values to registers. This is only set up for
126 // instruction values that are used outside of the block that defines
128 for (const BasicBlock &BB : *Fn) {
129 for (const Instruction &I : BB) {
130 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
131 Type *Ty = AI->getAllocatedType();
133 std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(Ty),
136 // Static allocas can be folded into the initial stack frame
137 // adjustment. For targets that don't realign the stack, don't
138 // do this if there is an extra alignment requirement.
139 if (AI->isStaticAlloca() &&
140 (TFI->isStackRealignable() || (Align <= StackAlign))) {
141 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
142 uint64_t TySize = MF->getDataLayout().getTypeAllocSize(Ty);
144 TySize *= CUI->getZExtValue(); // Get total allocated size.
145 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
146 int FrameIndex = INT_MAX;
147 auto Iter = CatchObjects.find(AI);
148 if (Iter != CatchObjects.end() && TLI->needsFixedCatchObjects()) {
149 FrameIndex = MF->getFrameInfo().CreateFixedObject(
150 TySize, 0, /*Immutable=*/false, /*isAliased=*/true);
151 MF->getFrameInfo().setObjectAlignment(FrameIndex, Align);
154 MF->getFrameInfo().CreateStackObject(TySize, Align, false, AI);
157 StaticAllocaMap[AI] = FrameIndex;
158 // Update the catch handler information.
159 if (Iter != CatchObjects.end()) {
160 for (int *CatchObjPtr : Iter->second)
161 *CatchObjPtr = FrameIndex;
164 // FIXME: Overaligned static allocas should be grouped into
165 // a single dynamic allocation instead of using a separate
166 // stack allocation for each one.
167 if (Align <= StackAlign)
169 // Inform the Frame Information that we have variable-sized objects.
170 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, AI);
174 // Look for inline asm that clobbers the SP register.
175 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
176 ImmutableCallSite CS(&I);
177 if (isa<InlineAsm>(CS.getCalledValue())) {
178 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
179 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
180 std::vector<TargetLowering::AsmOperandInfo> Ops =
181 TLI->ParseConstraints(Fn->getParent()->getDataLayout(), TRI, CS);
182 for (TargetLowering::AsmOperandInfo &Op : Ops) {
183 if (Op.Type == InlineAsm::isClobber) {
184 // Clobbers don't have SDValue operands, hence SDValue().
185 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
186 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
187 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
189 if (PhysReg.first == SP)
190 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
196 // Look for calls to the @llvm.va_start intrinsic. We can omit some
197 // prologue boilerplate for variadic functions that don't examine their
199 if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
200 if (II->getIntrinsicID() == Intrinsic::vastart)
201 MF->getFrameInfo().setHasVAStart(true);
204 // If we have a musttail call in a variadic function, we need to ensure we
205 // forward implicit register parameters.
206 if (const auto *CI = dyn_cast<CallInst>(&I)) {
207 if (CI->isMustTailCall() && Fn->isVarArg())
208 MF->getFrameInfo().setHasMustTailInVarArgFunc(true);
211 // Mark values used outside their block as exported, by allocating
212 // a virtual register for them.
213 if (isUsedOutsideOfDefiningBlock(&I))
214 if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(&I)))
215 InitializeRegForValue(&I);
217 // Collect llvm.dbg.declare information. This is done now instead of
218 // during the initial isel pass through the IR so that it is done
219 // in a predictable order.
220 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I)) {
221 assert(DI->getVariable() && "Missing variable");
222 assert(DI->getDebugLoc() && "Missing location");
223 if (MMI.hasDebugInfo()) {
224 // Don't handle byval struct arguments or VLAs, for example.
225 // Non-byval arguments are handled here (they refer to the stack
226 // temporary alloca at this point).
227 const Value *Address = DI->getAddress();
229 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
230 Address = BCI->getOperand(0);
231 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
232 DenseMap<const AllocaInst *, int>::iterator SI =
233 StaticAllocaMap.find(AI);
234 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
236 MF->setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
237 FI, DI->getDebugLoc());
244 // Decide the preferred extend type for a value.
245 PreferredExtendType[&I] = getPreferredExtendForValue(&I);
249 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
250 // also creates the initial PHI MachineInstrs, though none of the input
251 // operands are populated.
252 for (const BasicBlock &BB : *Fn) {
253 // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
254 // are really data, and no instructions can live here.
256 const Instruction *PadInst = BB.getFirstNonPHI();
257 // If this is a non-landingpad EH pad, mark this function as using
259 // FIXME: SEH catchpads do not create funclets, so we could avoid setting
260 // this in such cases in order to improve frame layout.
261 if (!isa<LandingPadInst>(PadInst)) {
262 MF->setHasEHFunclets(true);
263 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
265 if (isa<CatchSwitchInst>(PadInst)) {
266 assert(&*BB.begin() == PadInst &&
267 "WinEHPrepare failed to remove PHIs from imaginary BBs");
270 if (isa<FuncletPadInst>(PadInst))
271 assert(&*BB.begin() == PadInst && "WinEHPrepare failed to demote PHIs");
274 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&BB);
278 // Transfer the address-taken flag. This is necessary because there could
279 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
280 // the first one should be marked.
281 if (BB.hasAddressTaken())
282 MBB->setHasAddressTaken();
284 // Mark landing pad blocks.
288 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
290 for (BasicBlock::const_iterator I = BB.begin();
291 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
292 if (PN->use_empty()) continue;
295 if (PN->getType()->isEmptyTy())
298 DebugLoc DL = PN->getDebugLoc();
299 unsigned PHIReg = ValueMap[PN];
300 assert(PHIReg && "PHI node does not have an assigned virtual register!");
302 SmallVector<EVT, 4> ValueVTs;
303 ComputeValueVTs(*TLI, MF->getDataLayout(), PN->getType(), ValueVTs);
304 for (EVT VT : ValueVTs) {
305 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
306 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
307 for (unsigned i = 0; i != NumRegisters; ++i)
308 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
309 PHIReg += NumRegisters;
314 if (!isFuncletEHPersonality(Personality))
317 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
319 // Map all BB references in the WinEH data to MBBs.
320 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
321 for (WinEHHandlerType &H : TBME.HandlerArray) {
323 H.Handler = MBBMap[H.Handler.get<const BasicBlock *>()];
326 for (CxxUnwindMapEntry &UME : EHInfo.CxxUnwindMap)
328 UME.Cleanup = MBBMap[UME.Cleanup.get<const BasicBlock *>()];
329 for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap) {
330 const BasicBlock *BB = UME.Handler.get<const BasicBlock *>();
331 UME.Handler = MBBMap[BB];
333 for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap) {
334 const BasicBlock *BB = CME.Handler.get<const BasicBlock *>();
335 CME.Handler = MBBMap[BB];
339 /// clear - Clear out all the function-specific state. This returns this
340 /// FunctionLoweringInfo to an empty state, ready to be used for a
341 /// different function.
342 void FunctionLoweringInfo::clear() {
345 StaticAllocaMap.clear();
346 LiveOutRegInfo.clear();
348 ArgDbgValues.clear();
349 ByValArgFrameIndexMap.clear();
351 StatepointStackSlots.clear();
352 StatepointSpillMaps.clear();
353 PreferredExtendType.clear();
356 /// CreateReg - Allocate a single virtual register for the given type.
357 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
358 return RegInfo->createVirtualRegister(
359 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
362 /// CreateRegs - Allocate the appropriate number of virtual registers of
363 /// the correctly promoted or expanded types. Assign these registers
364 /// consecutive vreg numbers and return the first assigned number.
366 /// In the case that the given value has struct or array type, this function
367 /// will assign registers for each member or element.
369 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
370 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
372 SmallVector<EVT, 4> ValueVTs;
373 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
375 unsigned FirstReg = 0;
376 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
377 EVT ValueVT = ValueVTs[Value];
378 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
380 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
381 for (unsigned i = 0; i != NumRegs; ++i) {
382 unsigned R = CreateReg(RegisterVT);
383 if (!FirstReg) FirstReg = R;
389 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
390 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
391 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
392 /// the larger bit width by zero extension. The bit width must be no smaller
393 /// than the LiveOutInfo's existing bit width.
394 const FunctionLoweringInfo::LiveOutInfo *
395 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
396 if (!LiveOutRegInfo.inBounds(Reg))
399 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
403 if (BitWidth > LOI->KnownZero.getBitWidth()) {
404 LOI->NumSignBits = 1;
405 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
406 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
412 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
413 /// register based on the LiveOutInfo of its operands.
414 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
415 Type *Ty = PN->getType();
416 if (!Ty->isIntegerTy() || Ty->isVectorTy())
419 SmallVector<EVT, 1> ValueVTs;
420 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
421 assert(ValueVTs.size() == 1 &&
422 "PHIs with non-vector integer types should have a single VT.");
423 EVT IntVT = ValueVTs[0];
425 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
427 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
428 unsigned BitWidth = IntVT.getSizeInBits();
430 unsigned DestReg = ValueMap[PN];
431 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
433 LiveOutRegInfo.grow(DestReg);
434 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
436 Value *V = PN->getIncomingValue(0);
437 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
438 DestLOI.NumSignBits = 1;
439 APInt Zero(BitWidth, 0);
440 DestLOI.KnownZero = Zero;
441 DestLOI.KnownOne = Zero;
445 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
446 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
447 DestLOI.NumSignBits = Val.getNumSignBits();
448 DestLOI.KnownZero = ~Val;
449 DestLOI.KnownOne = Val;
451 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
452 "CopyToReg node was created.");
453 unsigned SrcReg = ValueMap[V];
454 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
455 DestLOI.IsValid = false;
458 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
460 DestLOI.IsValid = false;
466 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
467 DestLOI.KnownOne.getBitWidth() == BitWidth &&
468 "Masks should have the same bit width as the type.");
470 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
471 Value *V = PN->getIncomingValue(i);
472 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
473 DestLOI.NumSignBits = 1;
474 APInt Zero(BitWidth, 0);
475 DestLOI.KnownZero = Zero;
476 DestLOI.KnownOne = Zero;
480 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
481 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
482 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
483 DestLOI.KnownZero &= ~Val;
484 DestLOI.KnownOne &= Val;
488 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
489 "its CopyToReg node was created.");
490 unsigned SrcReg = ValueMap[V];
491 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
492 DestLOI.IsValid = false;
495 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
497 DestLOI.IsValid = false;
500 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
501 DestLOI.KnownZero &= SrcLOI->KnownZero;
502 DestLOI.KnownOne &= SrcLOI->KnownOne;
506 /// setArgumentFrameIndex - Record frame index for the byval
507 /// argument. This overrides previous frame index entry for this argument,
509 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
511 ByValArgFrameIndexMap[A] = FI;
514 /// getArgumentFrameIndex - Get frame index for the byval argument.
515 /// If the argument does not have any assigned frame index then 0 is
517 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
518 DenseMap<const Argument *, int>::iterator I =
519 ByValArgFrameIndexMap.find(A);
520 if (I != ByValArgFrameIndexMap.end())
522 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
526 unsigned FunctionLoweringInfo::getCatchPadExceptionPointerVReg(
527 const Value *CPI, const TargetRegisterClass *RC) {
528 MachineRegisterInfo &MRI = MF->getRegInfo();
529 auto I = CatchPadExceptionPointers.insert({CPI, 0});
530 unsigned &VReg = I.first->second;
532 VReg = MRI.createVirtualRegister(RC);
533 assert(VReg && "null vreg in exception pointer table!");
538 FunctionLoweringInfo::getOrCreateSwiftErrorVReg(const MachineBasicBlock *MBB,
540 auto Key = std::make_pair(MBB, Val);
541 auto It = SwiftErrorVRegDefMap.find(Key);
542 // If this is the first use of this swifterror value in this basic block,
543 // create a new virtual register.
544 // After we processed all basic blocks we will satisfy this "upwards exposed
545 // use" by inserting a copy or phi at the beginning of this block.
546 if (It == SwiftErrorVRegDefMap.end()) {
547 auto &DL = MF->getDataLayout();
548 const TargetRegisterClass *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
549 auto VReg = MF->getRegInfo().createVirtualRegister(RC);
550 SwiftErrorVRegDefMap[Key] = VReg;
551 SwiftErrorVRegUpwardsUse[Key] = VReg;
553 } else return It->second;
556 void FunctionLoweringInfo::setCurrentSwiftErrorVReg(
557 const MachineBasicBlock *MBB, const Value *Val, unsigned VReg) {
558 SwiftErrorVRegDefMap[std::make_pair(MBB, Val)] = VReg;