blob: a7f5ba1269eaade4133b19bce0e426e3e6a3520d [file] [log] [blame]
Dan Gohmana3624b62009-11-23 17:16:22 +00001//===-- 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
Dan Gohmane7846162010-07-07 16:01:37 +000015#include "llvm/CodeGen/FunctionLoweringInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#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"
David Majnemercde33032015-03-30 22:58:10 +000023#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000025#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#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"
Dan Gohmana3624b62009-11-23 17:16:22 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Hans Wennborgacb842d2014-03-05 02:43:26 +000036#include "llvm/Target/TargetFrameLowering.h"
Chandler Carruth92051402014-03-05 10:30:38 +000037#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetOptions.h"
40#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohmana3624b62009-11-23 17:16:22 +000042#include <algorithm>
43using namespace llvm;
44
Chandler Carruth1b9dde02014-04-22 02:02:50 +000045#define DEBUG_TYPE "function-lowering-info"
46
Dan Gohmana3624b62009-11-23 17:16:22 +000047/// 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.
Dan Gohman913c9982010-04-15 04:33:49 +000050static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
Dan Gohman7c845e42010-04-20 14:50:13 +000051 if (I->use_empty()) return false;
Dan Gohmana3624b62009-11-23 17:16:22 +000052 if (isa<PHINode>(I)) return true;
Dan Gohman913c9982010-04-15 04:33:49 +000053 const BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +000054 for (const User *U : I->users())
Gabor Greif52617fc2010-07-09 16:08:33 +000055 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
Dan Gohmana3624b62009-11-23 17:16:22 +000056 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +000057
Dan Gohmana3624b62009-11-23 17:16:22 +000058 return false;
59}
60
Jiangning Liuffbc6902014-09-19 05:30:35 +000061static 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.
65 //
66 // With this optimization, we would be able to reduce some redundant sign or
67 // zero extension instruction, and eventually more machine CSE opportunities
68 // can be exposed.
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();
75 }
76 }
77 if (NumOfSigned > NumOfUnsigned)
78 ExtendKind = ISD::SIGN_EXTEND;
79
80 return ExtendKind;
81}
82
Hans Wennborgacb842d2014-03-05 02:43:26 +000083void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
84 SelectionDAG *DAG) {
Dan Gohmana3624b62009-11-23 17:16:22 +000085 Fn = &fn;
86 MF = &mf;
Eric Christopher2ae2de72014-10-09 00:57:31 +000087 TLI = MF->getSubtarget().getTargetLowering();
Dan Gohmana3624b62009-11-23 17:16:22 +000088 RegInfo = &MF->getRegInfo();
David Majnemercde33032015-03-30 22:58:10 +000089 MachineModuleInfo &MMI = MF->getMMI();
Dan Gohmana3624b62009-11-23 17:16:22 +000090
Dan Gohmand7b5ce32010-07-10 09:00:22 +000091 // Check whether the function can return without sret-demotion.
92 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini56228da2015-07-09 01:57:34 +000093 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
94 mf.getDataLayout());
Bill Wendling8db01cb2013-06-06 00:11:39 +000095 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
Eric Christopher2ae2de72014-10-09 00:57:31 +000096 Fn->isVarArg(), Outs, Fn->getContext());
Dan Gohmand7b5ce32010-07-10 09:00:22 +000097
Dan Gohmana3624b62009-11-23 17:16:22 +000098 // 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
100 // them.
Dan Gohman913c9982010-04-15 04:33:49 +0000101 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
Dan Gohmana3624b62009-11-23 17:16:22 +0000102 for (; BB != EB; ++BB)
Eric Christopher219d51d2012-02-24 01:59:01 +0000103 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
104 I != E; ++I) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000105 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000106 // 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();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +0000110 uint64_t TySize = MF->getDataLayout().getTypeAllocSize(Ty);
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000111 unsigned Align =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +0000112 std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(Ty),
Eric Christopher2ae2de72014-10-09 00:57:31 +0000113 AI->getAlignment());
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000114
115 TySize *= CUI->getZExtValue(); // Get total allocated size.
116 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
117
118 StaticAllocaMap[AI] =
119 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
120
121 } else {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +0000122 unsigned Align =
123 std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(
124 AI->getAllocatedType()),
125 AI->getAlignment());
Eric Christopherd9134482014-08-04 21:25:23 +0000126 unsigned StackAlign =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000127 MF->getSubtarget().getFrameLowering()->getStackAlignment();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000128 if (Align <= StackAlign)
129 Align = 0;
130 // Inform the Frame Information that we have variable-sized objects.
131 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
132 }
133 }
134
135 // Look for inline asm that clobbers the SP register.
136 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
137 ImmutableCallSite CS(I);
Hans Wennborg0c72fd22014-03-05 03:21:23 +0000138 if (isa<InlineAsm>(CS.getCalledValue())) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000139 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Eric Christopher11e4df72015-02-26 22:38:43 +0000140 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000141 std::vector<TargetLowering::AsmOperandInfo> Ops =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +0000142 TLI->ParseConstraints(Fn->getParent()->getDataLayout(), TRI, CS);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000143 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);
Eric Christopher2ae2de72014-10-09 00:57:31 +0000148 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
Eric Christopher11e4df72015-02-26 22:38:43 +0000149 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
150 Op.ConstraintVT);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000151 if (PhysReg.first == SP)
Reid Klecknere69bdb82015-07-07 23:45:58 +0000152 MF->getFrameInfo()->setHasOpaqueSPAdjustment(true);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000153 }
154 }
155 }
156 }
157
Reid Kleckner2d9bb652014-08-22 21:59:26 +0000158 // Look for calls to the @llvm.va_start intrinsic. We can omit some
159 // prologue boilerplate for variadic functions that don't examine their
160 // arguments.
161 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
162 if (II->getIntrinsicID() == Intrinsic::vastart)
163 MF->getFrameInfo()->setHasVAStart(true);
164 }
165
Reid Kleckner16e55412014-08-29 21:42:08 +0000166 // If we have a musttail call in a variadic funciton, we need to ensure we
167 // forward implicit register parameters.
Reid Klecknerdccd0cb2014-08-29 21:42:21 +0000168 if (const auto *CI = dyn_cast<CallInst>(I)) {
Reid Kleckner16e55412014-08-29 21:42:08 +0000169 if (CI->isMustTailCall() && Fn->isVarArg())
170 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
171 }
172
Dan Gohman1e9362772010-07-16 17:54:27 +0000173 // Mark values used outside their block as exported, by allocating
174 // a virtual register for them.
Cameron Zwarichf8b22b32011-02-22 03:24:52 +0000175 if (isUsedOutsideOfDefiningBlock(I))
Dan Gohmana3624b62009-11-23 17:16:22 +0000176 if (!isa<AllocaInst>(I) ||
177 !StaticAllocaMap.count(cast<AllocaInst>(I)))
178 InitializeRegForValue(I);
179
Dan Gohman1e9362772010-07-16 17:54:27 +0000180 // 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)) {
Duncan P. N. Exon Smithd4a19a32015-04-21 18:24:23 +0000184 assert(DI->getVariable() && "Missing variable");
185 assert(DI->getDebugLoc() && "Missing location");
186 if (MMI.hasDebugInfo()) {
Dan Gohman1e9362772010-07-16 17:54:27 +0000187 // 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();
191 if (Address) {
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.
198 int FI = SI->second;
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000199 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
Dan Gohman1e9362772010-07-16 17:54:27 +0000200 FI, DI->getDebugLoc());
201 }
202 }
203 }
204 }
205 }
Jiangning Liuffbc6902014-09-19 05:30:35 +0000206
207 // Decide the preferred extend type for a value.
208 PreferredExtendType[I] = getPreferredExtendForValue(I);
Dan Gohman1e9362772010-07-16 17:54:27 +0000209 }
210
Dan Gohmana3624b62009-11-23 17:16:22 +0000211 // 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.
Dan Gohmanf57117d2010-04-14 16:30:40 +0000214 for (BB = Fn->begin(); BB != EB; ++BB) {
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000215 // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
216 // are really data, and no instructions can live here.
217 if (BB->isEHPad()) {
218 const Instruction *I = BB->getFirstNonPHI();
David Majnemer7735a6d2015-10-06 23:31:59 +0000219 // FIXME: Don't mark SEH functions without __finally blocks as having
220 // funclets.
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000221 if (!isa<LandingPadInst>(I))
222 MMI.setHasEHFunclets(true);
David Majnemer7735a6d2015-10-06 23:31:59 +0000223 if (isa<CatchEndPadInst>(I) || isa<CleanupEndPadInst>(I)) {
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000224 assert(&*BB->begin() == I &&
225 "WinEHPrepare failed to remove PHIs from imaginary BBs");
226 continue;
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000227 }
David Majnemer7735a6d2015-10-06 23:31:59 +0000228 if (isa<CatchPadInst>(I) || isa<CleanupPadInst>(I))
229 assert(&*BB->begin() == I && "WinEHPrepare failed to demote PHIs");
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000230 }
231
Dan Gohmana3624b62009-11-23 17:16:22 +0000232 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
233 MBBMap[BB] = MBB;
234 MF->push_back(MBB);
235
236 // Transfer the address-taken flag. This is necessary because there could
237 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
238 // the first one should be marked.
239 if (BB->hasAddressTaken())
240 MBB->setHasAddressTaken();
241
242 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
243 // appropriate.
Dan Gohman0f055d32010-04-20 14:46:25 +0000244 for (BasicBlock::const_iterator I = BB->begin();
245 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
246 if (PN->use_empty()) continue;
Dan Gohmana3624b62009-11-23 17:16:22 +0000247
Rafael Espindolae53b7d12011-05-13 15:18:06 +0000248 // Skip empty types
249 if (PN->getType()->isEmptyTy())
250 continue;
251
Dan Gohman7b7f0882010-04-20 14:48:02 +0000252 DebugLoc DL = PN->getDebugLoc();
Dan Gohmana3624b62009-11-23 17:16:22 +0000253 unsigned PHIReg = ValueMap[PN];
254 assert(PHIReg && "PHI node does not have an assigned virtual register!");
255
256 SmallVector<EVT, 4> ValueVTs;
Mehdi Amini56228da2015-07-09 01:57:34 +0000257 ComputeValueVTs(*TLI, MF->getDataLayout(), PN->getType(), ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000258 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
259 EVT VT = ValueVTs[vti];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000260 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
Eric Christopherfc6de422014-08-05 02:39:49 +0000261 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Dan Gohmana3624b62009-11-23 17:16:22 +0000262 for (unsigned i = 0; i != NumRegisters; ++i)
Chris Lattnerb06015a2010-02-09 19:54:29 +0000263 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
Dan Gohmana3624b62009-11-23 17:16:22 +0000264 PHIReg += NumRegisters;
265 }
266 }
267 }
Dan Gohman69e8e322010-04-14 16:32:56 +0000268
269 // Mark landing pad blocks.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000270 SmallVector<const LandingPadInst *, 4> LPads;
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000271 for (BB = Fn->begin(); BB != EB; ++BB) {
Reid Kleckner0e288232015-08-27 23:27:47 +0000272 const Instruction *FNP = BB->getFirstNonPHI();
Reid Kleckner78783912015-09-10 00:25:23 +0000273 if (BB->isEHPad() && MBBMap.count(BB))
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000274 MBBMap[BB]->setIsEHPad();
Reid Kleckner0e288232015-08-27 23:27:47 +0000275 if (const auto *LPI = dyn_cast<LandingPadInst>(FNP))
276 LPads.push_back(LPI);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000277 }
David Majnemercde33032015-03-30 22:58:10 +0000278
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000279 // If this personality uses funclets, we need to do a bit more work.
Reid Kleckner0e288232015-08-27 23:27:47 +0000280 if (!Fn->hasPersonalityFn())
281 return;
282 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000283 if (!isFuncletEHPersonality(Personality))
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000284 return;
285
Reid Klecknerf12c0302015-06-09 21:42:19 +0000286 if (Personality == EHPersonality::MSVC_Win64SEH ||
287 Personality == EHPersonality::MSVC_X86SEH) {
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000288 addSEHHandlersForLPads(LPads);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000289 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000290
Reid Kleckner94b704c2015-09-09 21:10:03 +0000291 // Calculate state numbers if we haven't already.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000292 WinEHFuncInfo &EHInfo = MMI.getWinEHFuncInfo(&fn);
Reid Kleckner78783912015-09-10 00:25:23 +0000293 const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
294 if (Personality == EHPersonality::MSVC_CXX)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000295 calculateWinCXXEHStateNumbers(WinEHParentFn, EHInfo);
David Majnemerf828a0c2015-10-01 18:44:59 +0000296 else if (isAsynchronousEHPersonality(Personality))
Reid Kleckner94b704c2015-09-09 21:10:03 +0000297 calculateSEHStateNumbers(WinEHParentFn, EHInfo);
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000298 else if (Personality == EHPersonality::CoreCLR)
299 calculateClrEHStateNumbers(WinEHParentFn, EHInfo);
Reid Kleckner78783912015-09-10 00:25:23 +0000300
David Majnemerf828a0c2015-10-01 18:44:59 +0000301 calculateCatchReturnSuccessorColors(WinEHParentFn, EHInfo);
302
Reid Kleckner78783912015-09-10 00:25:23 +0000303 // Map all BB references in the WinEH data to MBBs.
Reid Klecknerb005d282015-09-16 20:16:27 +0000304 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
305 for (WinEHHandlerType &H : TBME.HandlerArray) {
306 if (H.CatchObjRecoverIdx == -2 && H.CatchObj.Alloca) {
307 assert(StaticAllocaMap.count(H.CatchObj.Alloca));
308 H.CatchObj.FrameIndex = StaticAllocaMap[H.CatchObj.Alloca];
309 } else {
310 H.CatchObj.FrameIndex = INT_MAX;
311 }
312 if (const auto *BB = dyn_cast<BasicBlock>(H.Handler.get<const Value *>()))
Reid Kleckner78783912015-09-10 00:25:23 +0000313 H.Handler = MBBMap[BB];
Reid Klecknerb005d282015-09-16 20:16:27 +0000314 }
315 }
Reid Kleckner78783912015-09-10 00:25:23 +0000316 for (WinEHUnwindMapEntry &UME : EHInfo.UnwindMap)
317 if (UME.Cleanup)
318 if (const auto *BB = dyn_cast<BasicBlock>(UME.Cleanup.get<const Value *>()))
319 UME.Cleanup = MBBMap[BB];
320 for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap) {
321 const BasicBlock *BB = UME.Handler.get<const BasicBlock *>();
322 UME.Handler = MBBMap[BB];
Reid Kleckner94b704c2015-09-09 21:10:03 +0000323 }
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000324 for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap) {
325 const BasicBlock *BB = CME.Handler.get<const BasicBlock *>();
326 CME.Handler = MBBMap[BB];
327 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000328
Reid Kleckner94b704c2015-09-09 21:10:03 +0000329 // If there's an explicit EH registration node on the stack, record its
330 // frame index.
331 if (EHInfo.EHRegNode && EHInfo.EHRegNode->getParent()->getParent() == Fn) {
332 assert(StaticAllocaMap.count(EHInfo.EHRegNode));
333 EHInfo.EHRegNodeFrameIndex = StaticAllocaMap[EHInfo.EHRegNode];
Reid Klecknerf12c0302015-06-09 21:42:19 +0000334 }
335
336 // Copy the state numbers to LandingPadInfo for the current function, which
337 // could be a handler or the parent. This should happen for 32-bit SEH and
338 // C++ EH.
339 if (Personality == EHPersonality::MSVC_CXX ||
340 Personality == EHPersonality::MSVC_X86SEH) {
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000341 for (const LandingPadInst *LP : LPads) {
342 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
David Majnemer0ad363e2015-08-18 19:07:12 +0000343 MMI.addWinEHState(LPadMBB, EHInfo.EHPadStateMap[LP]);
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000344 }
David Majnemera225a192015-03-31 22:35:44 +0000345 }
David Majnemercde33032015-03-30 22:58:10 +0000346}
347
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000348void FunctionLoweringInfo::addSEHHandlersForLPads(
349 ArrayRef<const LandingPadInst *> LPads) {
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000350 MachineModuleInfo &MMI = MF->getMMI();
351
352 // Iterate over all landing pads with llvm.eh.actions calls.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000353 for (const LandingPadInst *LP : LPads) {
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000354 const IntrinsicInst *ActionsCall =
355 dyn_cast<IntrinsicInst>(LP->getNextNode());
356 if (!ActionsCall ||
357 ActionsCall->getIntrinsicID() != Intrinsic::eh_actions)
358 continue;
359
360 // Parse the llvm.eh.actions call we found.
361 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
Benjamin Kramera48e0652015-05-16 15:40:03 +0000362 SmallVector<std::unique_ptr<ActionHandler>, 4> Actions;
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000363 parseEHActions(ActionsCall, Actions);
364
365 // Iterate EH actions from most to least precedence, which means
366 // iterating in reverse.
367 for (auto I = Actions.rbegin(), E = Actions.rend(); I != E; ++I) {
Benjamin Kramera48e0652015-05-16 15:40:03 +0000368 ActionHandler *Action = I->get();
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000369 if (auto *CH = dyn_cast<CatchHandler>(Action)) {
370 const auto *Filter =
371 dyn_cast<Function>(CH->getSelector()->stripPointerCasts());
372 assert((Filter || CH->getSelector()->isNullValue()) &&
373 "expected function or catch-all");
374 const auto *RecoverBA =
375 cast<BlockAddress>(CH->getHandlerBlockOrFunc());
376 MMI.addSEHCatchHandler(LPadMBB, Filter, RecoverBA);
377 } else {
378 assert(isa<CleanupHandler>(Action));
379 const auto *Fini = cast<Function>(Action->getHandlerBlockOrFunc());
380 MMI.addSEHCleanupHandler(LPadMBB, Fini);
381 }
382 }
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000383 }
384}
385
Dan Gohmana3624b62009-11-23 17:16:22 +0000386/// clear - Clear out all the function-specific state. This returns this
387/// FunctionLoweringInfo to an empty state, ready to be used for a
388/// different function.
389void FunctionLoweringInfo::clear() {
Dan Gohmanad0b3ea2010-04-14 17:11:23 +0000390 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
391 "Not all catch info was assigned to a landing pad!");
392
Dan Gohmana3624b62009-11-23 17:16:22 +0000393 MBBMap.clear();
394 ValueMap.clear();
395 StaticAllocaMap.clear();
396#ifndef NDEBUG
397 CatchInfoLost.clear();
398 CatchInfoFound.clear();
399#endif
400 LiveOutRegInfo.clear();
Cameron Zwarich988faf92011-02-24 10:00:13 +0000401 VisitedBBs.clear();
Evan Cheng6e822452010-04-28 23:08:54 +0000402 ArgDbgValues.clear();
Devang Patel86ec8b32010-08-31 22:22:42 +0000403 ByValArgFrameIndexMap.clear();
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000404 RegFixups.clear();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000405 StatepointStackSlots.clear();
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000406 StatepointRelocatedValues.clear();
Jiangning Liu3b096172014-09-24 03:22:56 +0000407 PreferredExtendType.clear();
Dan Gohmana3624b62009-11-23 17:16:22 +0000408}
409
Dan Gohman93f59202010-07-02 00:10:16 +0000410/// CreateReg - Allocate a single virtual register for the given type.
Patrik Hagglund5e6c3612012-12-13 06:34:11 +0000411unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
Eric Christopherd9134482014-08-04 21:25:23 +0000412 return RegInfo->createVirtualRegister(
Eric Christopher2ae2de72014-10-09 00:57:31 +0000413 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
Dan Gohmana3624b62009-11-23 17:16:22 +0000414}
415
Dan Gohman93f59202010-07-02 00:10:16 +0000416/// CreateRegs - Allocate the appropriate number of virtual registers of
Dan Gohmana3624b62009-11-23 17:16:22 +0000417/// the correctly promoted or expanded types. Assign these registers
418/// consecutive vreg numbers and return the first assigned number.
419///
420/// In the case that the given value has struct or array type, this function
421/// will assign registers for each member or element.
422///
Chris Lattner229907c2011-07-18 04:54:35 +0000423unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
Eric Christopher2ae2de72014-10-09 00:57:31 +0000424 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
Bill Wendling0ccf3102013-06-19 20:32:16 +0000425
Dan Gohmana3624b62009-11-23 17:16:22 +0000426 SmallVector<EVT, 4> ValueVTs;
Mehdi Amini56228da2015-07-09 01:57:34 +0000427 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000428
429 unsigned FirstReg = 0;
430 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
431 EVT ValueVT = ValueVTs[Value];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000432 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000433
Bill Wendling8db01cb2013-06-06 00:11:39 +0000434 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000435 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman93f59202010-07-02 00:10:16 +0000436 unsigned R = CreateReg(RegisterVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000437 if (!FirstReg) FirstReg = R;
438 }
439 }
440 return FirstReg;
441}
Dan Gohmanad97b3d2009-11-23 17:42:46 +0000442
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000443/// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
444/// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
445/// the register's LiveOutInfo is for a smaller bit width, it is extended to
446/// the larger bit width by zero extension. The bit width must be no smaller
447/// than the LiveOutInfo's existing bit width.
448const FunctionLoweringInfo::LiveOutInfo *
449FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
450 if (!LiveOutRegInfo.inBounds(Reg))
Craig Topperc0196b12014-04-14 00:51:57 +0000451 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000452
453 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
454 if (!LOI->IsValid)
Craig Topperc0196b12014-04-14 00:51:57 +0000455 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000456
Cameron Zwarichd2f30412011-02-25 01:10:55 +0000457 if (BitWidth > LOI->KnownZero.getBitWidth()) {
Cameron Zwarich4c82cd22011-02-25 01:11:01 +0000458 LOI->NumSignBits = 1;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000459 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
460 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
461 }
462
463 return LOI;
464}
465
466/// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
467/// register based on the LiveOutInfo of its operands.
468void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
Chris Lattner229907c2011-07-18 04:54:35 +0000469 Type *Ty = PN->getType();
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000470 if (!Ty->isIntegerTy() || Ty->isVectorTy())
471 return;
472
473 SmallVector<EVT, 1> ValueVTs;
Mehdi Amini56228da2015-07-09 01:57:34 +0000474 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000475 assert(ValueVTs.size() == 1 &&
476 "PHIs with non-vector integer types should have a single VT.");
477 EVT IntVT = ValueVTs[0];
478
Bill Wendling8db01cb2013-06-06 00:11:39 +0000479 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000480 return;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000481 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000482 unsigned BitWidth = IntVT.getSizeInBits();
483
484 unsigned DestReg = ValueMap[PN];
485 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
486 return;
487 LiveOutRegInfo.grow(DestReg);
488 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
489
490 Value *V = PN->getIncomingValue(0);
491 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
492 DestLOI.NumSignBits = 1;
493 APInt Zero(BitWidth, 0);
494 DestLOI.KnownZero = Zero;
495 DestLOI.KnownOne = Zero;
496 return;
497 }
498
499 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
500 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
501 DestLOI.NumSignBits = Val.getNumSignBits();
502 DestLOI.KnownZero = ~Val;
503 DestLOI.KnownOne = Val;
504 } else {
505 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
506 "CopyToReg node was created.");
507 unsigned SrcReg = ValueMap[V];
508 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
509 DestLOI.IsValid = false;
510 return;
511 }
512 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
513 if (!SrcLOI) {
514 DestLOI.IsValid = false;
515 return;
516 }
517 DestLOI = *SrcLOI;
518 }
519
520 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
521 DestLOI.KnownOne.getBitWidth() == BitWidth &&
522 "Masks should have the same bit width as the type.");
523
524 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
525 Value *V = PN->getIncomingValue(i);
526 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
527 DestLOI.NumSignBits = 1;
528 APInt Zero(BitWidth, 0);
529 DestLOI.KnownZero = Zero;
530 DestLOI.KnownOne = Zero;
Eric Christopher0713a9d2011-06-08 23:55:35 +0000531 return;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000532 }
533
534 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
535 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
536 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
537 DestLOI.KnownZero &= ~Val;
538 DestLOI.KnownOne &= Val;
539 continue;
540 }
541
542 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
543 "its CopyToReg node was created.");
544 unsigned SrcReg = ValueMap[V];
545 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
546 DestLOI.IsValid = false;
547 return;
548 }
549 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
550 if (!SrcLOI) {
551 DestLOI.IsValid = false;
552 return;
553 }
554 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
555 DestLOI.KnownZero &= SrcLOI->KnownZero;
556 DestLOI.KnownOne &= SrcLOI->KnownOne;
557 }
558}
559
Devang Patel9d904e12011-09-08 22:59:09 +0000560/// setArgumentFrameIndex - Record frame index for the byval
Devang Patel86ec8b32010-08-31 22:22:42 +0000561/// argument. This overrides previous frame index entry for this argument,
562/// if any.
Devang Patel9d904e12011-09-08 22:59:09 +0000563void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
Eric Christopher219d51d2012-02-24 01:59:01 +0000564 int FI) {
Devang Patel86ec8b32010-08-31 22:22:42 +0000565 ByValArgFrameIndexMap[A] = FI;
566}
Eric Christopher0713a9d2011-06-08 23:55:35 +0000567
Devang Patel9d904e12011-09-08 22:59:09 +0000568/// getArgumentFrameIndex - Get frame index for the byval argument.
Devang Patel86ec8b32010-08-31 22:22:42 +0000569/// If the argument does not have any assigned frame index then 0 is
570/// returned.
Devang Patel9d904e12011-09-08 22:59:09 +0000571int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
Eric Christopher0713a9d2011-06-08 23:55:35 +0000572 DenseMap<const Argument *, int>::iterator I =
Devang Patel86ec8b32010-08-31 22:22:42 +0000573 ByValArgFrameIndexMap.find(A);
574 if (I != ByValArgFrameIndexMap.end())
575 return I->second;
Eric Christopher18c6be72012-02-23 03:39:43 +0000576 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
Devang Patel86ec8b32010-08-31 22:22:42 +0000577 return 0;
578}
579
Michael J. Spencer8b98bf22012-02-22 19:06:13 +0000580/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
581/// being passed to this variadic function, and set the MachineModuleInfo's
582/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
583/// reference to _fltused on Windows, which will link in MSVCRT's
584/// floating-point support.
585void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
586 MachineModuleInfo *MMI)
587{
588 FunctionType *FT = cast<FunctionType>(
589 I.getCalledValue()->getType()->getContainedType(0));
590 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
591 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
592 Type* T = I.getArgOperand(i)->getType();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000593 for (auto i : post_order(T)) {
Michael J. Spencer8b98bf22012-02-22 19:06:13 +0000594 if (i->isFloatingPointTy()) {
595 MMI->setUsesVAFloatArgument(true);
596 return;
597 }
598 }
599 }
600 }
601}
602
Bill Wendling247fd3b2011-08-17 21:56:44 +0000603/// AddLandingPadInfo - Extract the exception handling information from the
604/// landingpad instruction and add them to the specified machine module info.
605void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
606 MachineBasicBlock *MBB) {
Reid Klecknere00faf82015-08-31 20:02:16 +0000607 if (const auto *PF = dyn_cast<Function>(
608 I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts()))
609 MMI.addPersonality(PF);
Bill Wendling247fd3b2011-08-17 21:56:44 +0000610
611 if (I.isCleanup())
612 MMI.addCleanup(MBB);
613
614 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
615 // but we need to do it this way because of how the DWARF EH emitter
616 // processes the clauses.
617 for (unsigned i = I.getNumClauses(); i != 0; --i) {
618 Value *Val = I.getClause(i - 1);
619 if (I.isCatch(i - 1)) {
620 MMI.addCatchTypeInfo(MBB,
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000621 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000622 } else {
623 // Add filters in a list.
624 Constant *CVal = cast<Constant>(Val);
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000625 SmallVector<const GlobalValue*, 4> FilterList;
Bill Wendling247fd3b2011-08-17 21:56:44 +0000626 for (User::op_iterator
627 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000628 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000629
630 MMI.addFilterTypeInfo(MBB, FilterList);
631 }
632 }
633}