blob: 64af04087e7761eef406b5a8374deeb6c53e972e [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
David Majnemercde33032015-03-30 22:58:10 +000083namespace {
84struct WinEHNumbering {
85 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo), NextState(0) {}
86
87 WinEHFuncInfo &FuncInfo;
88 int NextState;
89
90 SmallVector<ActionHandler *, 4> HandlerStack;
David Majnemera225a192015-03-31 22:35:44 +000091 SmallPtrSet<const Function *, 4> VisitedHandlers;
David Majnemercde33032015-03-30 22:58:10 +000092
93 int currentEHNumber() const {
94 return HandlerStack.empty() ? -1 : HandlerStack.back()->getEHState();
95 }
96
97 void parseEHActions(const IntrinsicInst *II,
98 SmallVectorImpl<ActionHandler *> &Actions);
99 void createUnwindMapEntry(int ToState, ActionHandler *AH);
David Majnemera225a192015-03-31 22:35:44 +0000100 void createTryBlockMapEntry(int TryLow, int TryHigh,
101 ArrayRef<CatchHandler *> Handlers);
102 void processCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
David Majnemercde33032015-03-30 22:58:10 +0000103 void calculateStateNumbers(const Function &F);
104};
105}
106
Hans Wennborgacb842d2014-03-05 02:43:26 +0000107void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
108 SelectionDAG *DAG) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000109 Fn = &fn;
110 MF = &mf;
Eric Christopher2ae2de72014-10-09 00:57:31 +0000111 TLI = MF->getSubtarget().getTargetLowering();
Dan Gohmana3624b62009-11-23 17:16:22 +0000112 RegInfo = &MF->getRegInfo();
David Majnemercde33032015-03-30 22:58:10 +0000113 MachineModuleInfo &MMI = MF->getMMI();
Dan Gohmana3624b62009-11-23 17:16:22 +0000114
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000115 // Check whether the function can return without sret-demotion.
116 SmallVector<ISD::OutputArg, 4> Outs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000117 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
118 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
Eric Christopher2ae2de72014-10-09 00:57:31 +0000119 Fn->isVarArg(), Outs, Fn->getContext());
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000120
Dan Gohmana3624b62009-11-23 17:16:22 +0000121 // Initialize the mapping of values to registers. This is only set up for
122 // instruction values that are used outside of the block that defines
123 // them.
Dan Gohman913c9982010-04-15 04:33:49 +0000124 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
Dan Gohmana3624b62009-11-23 17:16:22 +0000125 for (; BB != EB; ++BB)
Eric Christopher219d51d2012-02-24 01:59:01 +0000126 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
127 I != E; ++I) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000128 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000129 // Static allocas can be folded into the initial stack frame adjustment.
130 if (AI->isStaticAlloca()) {
131 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
132 Type *Ty = AI->getAllocatedType();
133 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
134 unsigned Align =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000135 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
136 AI->getAlignment());
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000137
138 TySize *= CUI->getZExtValue(); // Get total allocated size.
139 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
140
141 StaticAllocaMap[AI] =
142 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
143
144 } else {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000145 unsigned Align = std::max(
146 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
147 AI->getAllocatedType()),
148 AI->getAlignment());
Eric Christopherd9134482014-08-04 21:25:23 +0000149 unsigned StackAlign =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000150 MF->getSubtarget().getFrameLowering()->getStackAlignment();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000151 if (Align <= StackAlign)
152 Align = 0;
153 // Inform the Frame Information that we have variable-sized objects.
154 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
155 }
156 }
157
158 // Look for inline asm that clobbers the SP register.
159 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
160 ImmutableCallSite CS(I);
Hans Wennborg0c72fd22014-03-05 03:21:23 +0000161 if (isa<InlineAsm>(CS.getCalledValue())) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000162 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Eric Christopher11e4df72015-02-26 22:38:43 +0000163 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000164 std::vector<TargetLowering::AsmOperandInfo> Ops =
Eric Christopher11e4df72015-02-26 22:38:43 +0000165 TLI->ParseConstraints(TRI, CS);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000166 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
167 TargetLowering::AsmOperandInfo &Op = Ops[I];
168 if (Op.Type == InlineAsm::isClobber) {
169 // Clobbers don't have SDValue operands, hence SDValue().
170 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
Eric Christopher2ae2de72014-10-09 00:57:31 +0000171 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
Eric Christopher11e4df72015-02-26 22:38:43 +0000172 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
173 Op.ConstraintVT);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000174 if (PhysReg.first == SP)
175 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
176 }
177 }
178 }
179 }
180
Reid Kleckner2d9bb652014-08-22 21:59:26 +0000181 // Look for calls to the @llvm.va_start intrinsic. We can omit some
182 // prologue boilerplate for variadic functions that don't examine their
183 // arguments.
184 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
185 if (II->getIntrinsicID() == Intrinsic::vastart)
186 MF->getFrameInfo()->setHasVAStart(true);
187 }
188
Reid Kleckner16e55412014-08-29 21:42:08 +0000189 // If we have a musttail call in a variadic funciton, we need to ensure we
190 // forward implicit register parameters.
Reid Klecknerdccd0cb2014-08-29 21:42:21 +0000191 if (const auto *CI = dyn_cast<CallInst>(I)) {
Reid Kleckner16e55412014-08-29 21:42:08 +0000192 if (CI->isMustTailCall() && Fn->isVarArg())
193 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
194 }
195
Dan Gohman1e9362772010-07-16 17:54:27 +0000196 // Mark values used outside their block as exported, by allocating
197 // a virtual register for them.
Cameron Zwarichf8b22b32011-02-22 03:24:52 +0000198 if (isUsedOutsideOfDefiningBlock(I))
Dan Gohmana3624b62009-11-23 17:16:22 +0000199 if (!isa<AllocaInst>(I) ||
200 !StaticAllocaMap.count(cast<AllocaInst>(I)))
201 InitializeRegForValue(I);
202
Dan Gohman1e9362772010-07-16 17:54:27 +0000203 // Collect llvm.dbg.declare information. This is done now instead of
204 // during the initial isel pass through the IR so that it is done
205 // in a predictable order.
206 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
Manman Ren983a16c2013-06-28 05:43:10 +0000207 DIVariable DIVar(DI->getVariable());
208 assert((!DIVar || DIVar.isVariable()) &&
209 "Variable in DbgDeclareInst should be either null or a DIVariable.");
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000210 if (MMI.hasDebugInfo() && DIVar && DI->getDebugLoc()) {
Dan Gohman1e9362772010-07-16 17:54:27 +0000211 // Don't handle byval struct arguments or VLAs, for example.
212 // Non-byval arguments are handled here (they refer to the stack
213 // temporary alloca at this point).
214 const Value *Address = DI->getAddress();
215 if (Address) {
216 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
217 Address = BCI->getOperand(0);
218 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
219 DenseMap<const AllocaInst *, int>::iterator SI =
220 StaticAllocaMap.find(AI);
221 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
222 int FI = SI->second;
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000223 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
Dan Gohman1e9362772010-07-16 17:54:27 +0000224 FI, DI->getDebugLoc());
225 }
226 }
227 }
228 }
229 }
Jiangning Liuffbc6902014-09-19 05:30:35 +0000230
231 // Decide the preferred extend type for a value.
232 PreferredExtendType[I] = getPreferredExtendForValue(I);
Dan Gohman1e9362772010-07-16 17:54:27 +0000233 }
234
Dan Gohmana3624b62009-11-23 17:16:22 +0000235 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
236 // also creates the initial PHI MachineInstrs, though none of the input
237 // operands are populated.
Dan Gohmanf57117d2010-04-14 16:30:40 +0000238 for (BB = Fn->begin(); BB != EB; ++BB) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000239 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
240 MBBMap[BB] = MBB;
241 MF->push_back(MBB);
242
243 // Transfer the address-taken flag. This is necessary because there could
244 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
245 // the first one should be marked.
246 if (BB->hasAddressTaken())
247 MBB->setHasAddressTaken();
248
249 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
250 // appropriate.
Dan Gohman0f055d32010-04-20 14:46:25 +0000251 for (BasicBlock::const_iterator I = BB->begin();
252 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
253 if (PN->use_empty()) continue;
Dan Gohmana3624b62009-11-23 17:16:22 +0000254
Rafael Espindolae53b7d12011-05-13 15:18:06 +0000255 // Skip empty types
256 if (PN->getType()->isEmptyTy())
257 continue;
258
Dan Gohman7b7f0882010-04-20 14:48:02 +0000259 DebugLoc DL = PN->getDebugLoc();
Dan Gohmana3624b62009-11-23 17:16:22 +0000260 unsigned PHIReg = ValueMap[PN];
261 assert(PHIReg && "PHI node does not have an assigned virtual register!");
262
263 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000264 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000265 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
266 EVT VT = ValueVTs[vti];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000267 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
Eric Christopherfc6de422014-08-05 02:39:49 +0000268 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Dan Gohmana3624b62009-11-23 17:16:22 +0000269 for (unsigned i = 0; i != NumRegisters; ++i)
Chris Lattnerb06015a2010-02-09 19:54:29 +0000270 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
Dan Gohmana3624b62009-11-23 17:16:22 +0000271 PHIReg += NumRegisters;
272 }
273 }
274 }
Dan Gohman69e8e322010-04-14 16:32:56 +0000275
276 // Mark landing pad blocks.
277 for (BB = Fn->begin(); BB != EB; ++BB)
David Majnemercde33032015-03-30 22:58:10 +0000278 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
Dan Gohman69e8e322010-04-14 16:32:56 +0000279 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
David Majnemercde33032015-03-30 22:58:10 +0000280
281 // Calculate EH numbers for WinEH.
David Majnemera225a192015-03-31 22:35:44 +0000282 if (fn.getFnAttribute("wineh-parent").getValueAsString() == fn.getName()) {
283 WinEHNumbering Num(MMI.getWinEHFuncInfo(&fn));
284 Num.calculateStateNumbers(fn);
285 // Pop everything on the handler stack.
286 Num.processCallSite(None, ImmutableCallSite());
287 }
David Majnemercde33032015-03-30 22:58:10 +0000288}
289
290void WinEHNumbering::parseEHActions(const IntrinsicInst *II,
291 SmallVectorImpl<ActionHandler *> &Actions) {
292 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
293 uint64_t ActionKind =
294 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
295 if (ActionKind == /*catch=*/1) {
296 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
297 Value *CatchObject = II->getArgOperand(I + 2);
298 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
299 I += 4;
300 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
301 CH->setExceptionVar(CatchObject);
302 CH->setHandlerBlockOrFunc(Handler);
303 Actions.push_back(CH);
304 } else {
305 assert(ActionKind == 0 && "expected a cleanup or a catch action!");
306 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
307 I += 2;
308 auto *CH = new CleanupHandler(/*BB=*/nullptr);
309 CH->setHandlerBlockOrFunc(Handler);
310 Actions.push_back(CH);
311 }
312 }
313 std::reverse(Actions.begin(), Actions.end());
314}
315
316void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
317 WinEHUnwindMapEntry UME;
318 UME.ToState = ToState;
David Majnemera225a192015-03-31 22:35:44 +0000319 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
David Majnemercde33032015-03-30 22:58:10 +0000320 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
321 else
322 UME.Cleanup = nullptr;
323 FuncInfo.UnwindMap.push_back(UME);
324}
325
David Majnemera225a192015-03-31 22:35:44 +0000326void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
327 ArrayRef<CatchHandler *> Handlers) {
328 WinEHTryBlockMapEntry TBME;
329 TBME.TryLow = TryLow;
330 TBME.TryHigh = TryHigh;
331 // FIXME: This should be revisited when we want to throw inside a catch
332 // handler.
333 TBME.CatchHigh = INT_MAX;
334 assert(TBME.TryLow <= TBME.TryHigh);
335 assert(TBME.CatchHigh > TBME.TryHigh);
336 for (CatchHandler *CH : Handlers) {
337 WinEHHandlerType HT;
338 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
339 // Selectors are always pointers to GlobalVariables with 'struct' type.
340 // The struct has two fields, adjectives and a type descriptor.
341 auto *CS = cast<ConstantStruct>(GV->getInitializer());
342 HT.Adjectives =
343 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
344 HT.TypeDescriptor = cast<GlobalVariable>(
345 CS->getAggregateElement(1)->stripPointerCasts());
346 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
347 // FIXME: We don't support catching objects yet!
348 HT.CatchObjIdx = INT_MAX;
349 HT.CatchObjOffset = 0;
350 TBME.HandlerArray.push_back(HT);
351 }
352 FuncInfo.TryBlockMap.push_back(TBME);
353}
354
David Majnemercde33032015-03-30 22:58:10 +0000355static void print_name(const Value *V) {
David Majnemer9a555392015-03-30 23:14:45 +0000356#ifndef NDEBUG
David Majnemercde33032015-03-30 22:58:10 +0000357 if (!V) {
358 DEBUG(dbgs() << "null");
359 return;
360 }
361
362 if (const auto *F = dyn_cast<Function>(V))
363 DEBUG(dbgs() << F->getName());
364 else
365 DEBUG(V->dump());
David Majnemer9a555392015-03-30 23:14:45 +0000366#endif
David Majnemercde33032015-03-30 22:58:10 +0000367}
368
David Majnemera225a192015-03-31 22:35:44 +0000369void WinEHNumbering::processCallSite(ArrayRef<ActionHandler *> Actions,
370 ImmutableCallSite CS) {
David Majnemercde33032015-03-30 22:58:10 +0000371 int FirstMismatch = 0;
372 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
373 ++FirstMismatch) {
374 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
375 Actions[FirstMismatch]->getHandlerBlockOrFunc())
376 break;
377 delete Actions[FirstMismatch];
378 }
379
David Majnemera225a192015-03-31 22:35:44 +0000380 bool EnteringScope = (int)Actions.size() > FirstMismatch;
David Majnemera225a192015-03-31 22:35:44 +0000381
David Majnemercde33032015-03-30 22:58:10 +0000382 // Don't recurse while we are looping over the handler stack. Instead, defer
383 // the numbering of the catch handlers until we are done popping.
David Majnemera225a192015-03-31 22:35:44 +0000384 SmallVector<CatchHandler *, 4> PoppedCatches;
David Majnemercde33032015-03-30 22:58:10 +0000385 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
David Majnemera225a192015-03-31 22:35:44 +0000386 if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back())) {
387 PoppedCatches.push_back(CH);
388 } else {
389 // Delete cleanup handlers
390 delete HandlerStack.back();
391 }
David Majnemercde33032015-03-30 22:58:10 +0000392 HandlerStack.pop_back();
393 }
394
David Majnemera225a192015-03-31 22:35:44 +0000395 // We need to create a new state number if we are exiting a try scope and we
396 // will not push any more actions.
397 int TryHigh = NextState - 1;
David Majnemerd1079bf2015-03-31 22:43:56 +0000398 if (!EnteringScope && !PoppedCatches.empty()) {
David Majnemera225a192015-03-31 22:35:44 +0000399 createUnwindMapEntry(currentEHNumber(), nullptr);
400 ++NextState;
401 }
David Majnemercde33032015-03-30 22:58:10 +0000402
David Majnemera225a192015-03-31 22:35:44 +0000403 int LastTryLowIdx = 0;
404 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
405 CatchHandler *CH = PoppedCatches[I];
406 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
407 int TryLow = CH->getEHState();
408 auto Handlers =
409 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
410 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
411 LastTryLowIdx = I + 1;
412 }
413 }
414
415 for (CatchHandler *CH : PoppedCatches) {
416 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc()))
417 calculateStateNumbers(*F);
418 delete CH;
419 }
420
421 bool LastActionWasCatch = false;
David Majnemercde33032015-03-30 22:58:10 +0000422 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
David Majnemera225a192015-03-31 22:35:44 +0000423 // We can reuse eh states when pushing two catches for the same invoke.
424 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I]);
425 // FIXME: Reenable this optimization!
426 if (CurrActionIsCatch && LastActionWasCatch && false) {
427 Actions[I]->setEHState(currentEHNumber());
428 } else {
429 createUnwindMapEntry(currentEHNumber(), Actions[I]);
430 Actions[I]->setEHState(NextState);
431 NextState++;
432 DEBUG(dbgs() << "Creating unwind map entry for: (");
433 print_name(Actions[I]->getHandlerBlockOrFunc());
434 DEBUG(dbgs() << ", " << currentEHNumber() << ")\n");
435 }
David Majnemercde33032015-03-30 22:58:10 +0000436 HandlerStack.push_back(Actions[I]);
David Majnemera225a192015-03-31 22:35:44 +0000437 LastActionWasCatch = CurrActionIsCatch;
David Majnemercde33032015-03-30 22:58:10 +0000438 }
439
440 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
441 print_name(CS ? CS.getCalledValue() : nullptr);
442 DEBUG(dbgs() << '\n');
443}
444
445void WinEHNumbering::calculateStateNumbers(const Function &F) {
David Majnemera225a192015-03-31 22:35:44 +0000446 auto I = VisitedHandlers.insert(&F);
447 if (!I.second)
448 return; // We've already visited this handler, don't renumber it.
449
David Majnemercde33032015-03-30 22:58:10 +0000450 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
451 SmallVector<ActionHandler *, 4> ActionList;
452 for (const BasicBlock &BB : F) {
453 for (const Instruction &I : BB) {
454 const auto *CI = dyn_cast<CallInst>(&I);
455 if (!CI || CI->doesNotThrow())
456 continue;
David Majnemera225a192015-03-31 22:35:44 +0000457 processCallSite(None, CI);
David Majnemercde33032015-03-30 22:58:10 +0000458 }
459 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
460 if (!II)
461 continue;
462 const LandingPadInst *LPI = II->getLandingPadInst();
David Majnemera225a192015-03-31 22:35:44 +0000463 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
464 if (!ActionsCall)
465 continue;
466 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
467 parseEHActions(ActionsCall, ActionList);
468 processCallSite(ActionList, II);
469 ActionList.clear();
470 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
David Majnemercde33032015-03-30 22:58:10 +0000471 }
Dan Gohmana3624b62009-11-23 17:16:22 +0000472}
473
474/// clear - Clear out all the function-specific state. This returns this
475/// FunctionLoweringInfo to an empty state, ready to be used for a
476/// different function.
477void FunctionLoweringInfo::clear() {
Dan Gohmanad0b3ea2010-04-14 17:11:23 +0000478 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
479 "Not all catch info was assigned to a landing pad!");
480
Dan Gohmana3624b62009-11-23 17:16:22 +0000481 MBBMap.clear();
482 ValueMap.clear();
483 StaticAllocaMap.clear();
484#ifndef NDEBUG
485 CatchInfoLost.clear();
486 CatchInfoFound.clear();
487#endif
488 LiveOutRegInfo.clear();
Cameron Zwarich988faf92011-02-24 10:00:13 +0000489 VisitedBBs.clear();
Evan Cheng6e822452010-04-28 23:08:54 +0000490 ArgDbgValues.clear();
Devang Patel86ec8b32010-08-31 22:22:42 +0000491 ByValArgFrameIndexMap.clear();
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000492 RegFixups.clear();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000493 StatepointStackSlots.clear();
Jiangning Liu3b096172014-09-24 03:22:56 +0000494 PreferredExtendType.clear();
Dan Gohmana3624b62009-11-23 17:16:22 +0000495}
496
Dan Gohman93f59202010-07-02 00:10:16 +0000497/// CreateReg - Allocate a single virtual register for the given type.
Patrik Hagglund5e6c3612012-12-13 06:34:11 +0000498unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
Eric Christopherd9134482014-08-04 21:25:23 +0000499 return RegInfo->createVirtualRegister(
Eric Christopher2ae2de72014-10-09 00:57:31 +0000500 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
Dan Gohmana3624b62009-11-23 17:16:22 +0000501}
502
Dan Gohman93f59202010-07-02 00:10:16 +0000503/// CreateRegs - Allocate the appropriate number of virtual registers of
Dan Gohmana3624b62009-11-23 17:16:22 +0000504/// the correctly promoted or expanded types. Assign these registers
505/// consecutive vreg numbers and return the first assigned number.
506///
507/// In the case that the given value has struct or array type, this function
508/// will assign registers for each member or element.
509///
Chris Lattner229907c2011-07-18 04:54:35 +0000510unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
Eric Christopher2ae2de72014-10-09 00:57:31 +0000511 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
Bill Wendling0ccf3102013-06-19 20:32:16 +0000512
Dan Gohmana3624b62009-11-23 17:16:22 +0000513 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000514 ComputeValueVTs(*TLI, Ty, ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000515
516 unsigned FirstReg = 0;
517 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
518 EVT ValueVT = ValueVTs[Value];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000519 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000520
Bill Wendling8db01cb2013-06-06 00:11:39 +0000521 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000522 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman93f59202010-07-02 00:10:16 +0000523 unsigned R = CreateReg(RegisterVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000524 if (!FirstReg) FirstReg = R;
525 }
526 }
527 return FirstReg;
528}
Dan Gohmanad97b3d2009-11-23 17:42:46 +0000529
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000530/// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
531/// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
532/// the register's LiveOutInfo is for a smaller bit width, it is extended to
533/// the larger bit width by zero extension. The bit width must be no smaller
534/// than the LiveOutInfo's existing bit width.
535const FunctionLoweringInfo::LiveOutInfo *
536FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
537 if (!LiveOutRegInfo.inBounds(Reg))
Craig Topperc0196b12014-04-14 00:51:57 +0000538 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000539
540 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
541 if (!LOI->IsValid)
Craig Topperc0196b12014-04-14 00:51:57 +0000542 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000543
Cameron Zwarichd2f30412011-02-25 01:10:55 +0000544 if (BitWidth > LOI->KnownZero.getBitWidth()) {
Cameron Zwarich4c82cd22011-02-25 01:11:01 +0000545 LOI->NumSignBits = 1;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000546 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
547 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
548 }
549
550 return LOI;
551}
552
553/// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
554/// register based on the LiveOutInfo of its operands.
555void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
Chris Lattner229907c2011-07-18 04:54:35 +0000556 Type *Ty = PN->getType();
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000557 if (!Ty->isIntegerTy() || Ty->isVectorTy())
558 return;
559
560 SmallVector<EVT, 1> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000561 ComputeValueVTs(*TLI, Ty, ValueVTs);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000562 assert(ValueVTs.size() == 1 &&
563 "PHIs with non-vector integer types should have a single VT.");
564 EVT IntVT = ValueVTs[0];
565
Bill Wendling8db01cb2013-06-06 00:11:39 +0000566 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000567 return;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000568 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000569 unsigned BitWidth = IntVT.getSizeInBits();
570
571 unsigned DestReg = ValueMap[PN];
572 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
573 return;
574 LiveOutRegInfo.grow(DestReg);
575 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
576
577 Value *V = PN->getIncomingValue(0);
578 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
579 DestLOI.NumSignBits = 1;
580 APInt Zero(BitWidth, 0);
581 DestLOI.KnownZero = Zero;
582 DestLOI.KnownOne = Zero;
583 return;
584 }
585
586 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
587 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
588 DestLOI.NumSignBits = Val.getNumSignBits();
589 DestLOI.KnownZero = ~Val;
590 DestLOI.KnownOne = Val;
591 } else {
592 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
593 "CopyToReg node was created.");
594 unsigned SrcReg = ValueMap[V];
595 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
596 DestLOI.IsValid = false;
597 return;
598 }
599 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
600 if (!SrcLOI) {
601 DestLOI.IsValid = false;
602 return;
603 }
604 DestLOI = *SrcLOI;
605 }
606
607 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
608 DestLOI.KnownOne.getBitWidth() == BitWidth &&
609 "Masks should have the same bit width as the type.");
610
611 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
612 Value *V = PN->getIncomingValue(i);
613 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
614 DestLOI.NumSignBits = 1;
615 APInt Zero(BitWidth, 0);
616 DestLOI.KnownZero = Zero;
617 DestLOI.KnownOne = Zero;
Eric Christopher0713a9d2011-06-08 23:55:35 +0000618 return;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000619 }
620
621 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
622 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
623 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
624 DestLOI.KnownZero &= ~Val;
625 DestLOI.KnownOne &= Val;
626 continue;
627 }
628
629 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
630 "its CopyToReg node was created.");
631 unsigned SrcReg = ValueMap[V];
632 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
633 DestLOI.IsValid = false;
634 return;
635 }
636 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
637 if (!SrcLOI) {
638 DestLOI.IsValid = false;
639 return;
640 }
641 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
642 DestLOI.KnownZero &= SrcLOI->KnownZero;
643 DestLOI.KnownOne &= SrcLOI->KnownOne;
644 }
645}
646
Devang Patel9d904e12011-09-08 22:59:09 +0000647/// setArgumentFrameIndex - Record frame index for the byval
Devang Patel86ec8b32010-08-31 22:22:42 +0000648/// argument. This overrides previous frame index entry for this argument,
649/// if any.
Devang Patel9d904e12011-09-08 22:59:09 +0000650void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
Eric Christopher219d51d2012-02-24 01:59:01 +0000651 int FI) {
Devang Patel86ec8b32010-08-31 22:22:42 +0000652 ByValArgFrameIndexMap[A] = FI;
653}
Eric Christopher0713a9d2011-06-08 23:55:35 +0000654
Devang Patel9d904e12011-09-08 22:59:09 +0000655/// getArgumentFrameIndex - Get frame index for the byval argument.
Devang Patel86ec8b32010-08-31 22:22:42 +0000656/// If the argument does not have any assigned frame index then 0 is
657/// returned.
Devang Patel9d904e12011-09-08 22:59:09 +0000658int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
Eric Christopher0713a9d2011-06-08 23:55:35 +0000659 DenseMap<const Argument *, int>::iterator I =
Devang Patel86ec8b32010-08-31 22:22:42 +0000660 ByValArgFrameIndexMap.find(A);
661 if (I != ByValArgFrameIndexMap.end())
662 return I->second;
Eric Christopher18c6be72012-02-23 03:39:43 +0000663 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
Devang Patel86ec8b32010-08-31 22:22:42 +0000664 return 0;
665}
666
Michael J. Spencer8b98bf22012-02-22 19:06:13 +0000667/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
668/// being passed to this variadic function, and set the MachineModuleInfo's
669/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
670/// reference to _fltused on Windows, which will link in MSVCRT's
671/// floating-point support.
672void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
673 MachineModuleInfo *MMI)
674{
675 FunctionType *FT = cast<FunctionType>(
676 I.getCalledValue()->getType()->getContainedType(0));
677 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
678 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
679 Type* T = I.getArgOperand(i)->getType();
680 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
681 i != e; ++i) {
682 if (i->isFloatingPointTy()) {
683 MMI->setUsesVAFloatArgument(true);
684 return;
685 }
686 }
687 }
688 }
689}
690
Bill Wendling247fd3b2011-08-17 21:56:44 +0000691/// AddLandingPadInfo - Extract the exception handling information from the
692/// landingpad instruction and add them to the specified machine module info.
693void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
694 MachineBasicBlock *MBB) {
695 MMI.addPersonality(MBB,
696 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
697
698 if (I.isCleanup())
699 MMI.addCleanup(MBB);
700
701 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
702 // but we need to do it this way because of how the DWARF EH emitter
703 // processes the clauses.
704 for (unsigned i = I.getNumClauses(); i != 0; --i) {
705 Value *Val = I.getClause(i - 1);
706 if (I.isCatch(i - 1)) {
707 MMI.addCatchTypeInfo(MBB,
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000708 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000709 } else {
710 // Add filters in a list.
711 Constant *CVal = cast<Constant>(Val);
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000712 SmallVector<const GlobalValue*, 4> FilterList;
Bill Wendling247fd3b2011-08-17 21:56:44 +0000713 for (User::op_iterator
714 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000715 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000716
717 MMI.addFilterTypeInfo(MBB, FilterList);
718 }
719 }
720}