blob: 5a824ae8fe44b9b24c9972869946b741ddef3092 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the bison parser for LLVM assembly languages files.
11//
12//===----------------------------------------------------------------------===//
13
14%{
15#include "ParserInternals.h"
16#include "llvm/CallingConv.h"
17#include "llvm/InlineAsm.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/ValueSymbolTable.h"
Chandler Carrutha228e392007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/Streams.h"
Dale Johannesen98738822008-02-22 22:17:59 +000028#include "llvm/ParamAttrsList.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include <algorithm>
30#include <list>
31#include <map>
32#include <utility>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033
34// The following is a gross hack. In order to rid the libAsmParser library of
35// exceptions, we have to have a way of getting the yyparse function to go into
36// an error situation. So, whenever we want an error to occur, the GenerateError
37// function (see bottom of file) sets TriggerError. Then, at the end of each
38// production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
39// (a goto) to put YACC in error state. Furthermore, several calls to
40// GenerateError are made from inside productions and they must simulate the
41// previous exception behavior by exiting the production immediately. We have
42// replaced these with the GEN_ERROR macro which calls GeneratError and then
43// immediately invokes YYERROR. This would be so much cleaner if it was a
44// recursive descent parser.
45static bool TriggerError = false;
46#define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
47#define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
48
49int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
50int yylex(); // declaration" of xxx warnings.
51int yyparse();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052using namespace llvm;
53
54static Module *ParserResult;
55
56// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
57// relating to upreferences in the input stream.
58//
59//#define DEBUG_UPREFS 1
60#ifdef DEBUG_UPREFS
61#define UR_OUT(X) cerr << X
62#else
63#define UR_OUT(X)
64#endif
65
66#define YYERROR_VERBOSE 1
67
68static GlobalVariable *CurGV;
69
70
71// This contains info used when building the body of a function. It is
72// destroyed when the function is completed.
73//
74typedef std::vector<Value *> ValueList; // Numbered defs
75
76static void
77ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
78
79static struct PerModuleInfo {
80 Module *CurrentModule;
81 ValueList Values; // Module level numbered definitions
82 ValueList LateResolveValues;
83 std::vector<PATypeHolder> Types;
84 std::map<ValID, PATypeHolder> LateResolveTypes;
85
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
95 //
96 typedef std::map<std::pair<const PointerType *,
97 ValID>, GlobalValue*> GlobalRefsType;
98 GlobalRefsType GlobalRefs;
99
100 void ModuleDone() {
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
104 //
105 ResolveDefinitions(LateResolveValues);
106 if (TriggerError)
107 return;
108
109 // Check to make sure that all global value forward references have been
110 // resolved!
111 //
112 if (!GlobalRefs.empty()) {
113 std::string UndefinedReferences = "Unresolved global references exist:\n";
114
115 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
116 I != E; ++I) {
117 UndefinedReferences += " " + I->first.first->getDescription() + " " +
118 I->first.second.getName() + "\n";
119 }
120 GenerateError(UndefinedReferences);
121 return;
122 }
123
Chandler Carrutha228e392007-08-04 01:51:18 +0000124 // Look for intrinsic functions and CallInst that need to be upgraded
125 for (Module::iterator FI = CurrentModule->begin(),
126 FE = CurrentModule->end(); FI != FE; )
127 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
128
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 Values.clear(); // Clear out function local definitions
130 Types.clear();
131 CurrentModule = 0;
132 }
133
134 // GetForwardRefForGlobal - Check to see if there is a forward reference
135 // for this global. If so, remove it from the GlobalRefs map and return it.
136 // If not, just return null.
137 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
138 // Check to see if there is a forward reference to this global variable...
139 // if there is, eliminate it and patch the reference to use the new def'n.
140 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
141 GlobalValue *Ret = 0;
142 if (I != GlobalRefs.end()) {
143 Ret = I->second;
144 GlobalRefs.erase(I);
145 }
146 return Ret;
147 }
148
149 bool TypeIsUnresolved(PATypeHolder* PATy) {
150 // If it isn't abstract, its resolved
151 const Type* Ty = PATy->get();
152 if (!Ty->isAbstract())
153 return false;
154 // Traverse the type looking for abstract types. If it isn't abstract then
155 // we don't need to traverse that leg of the type.
156 std::vector<const Type*> WorkList, SeenList;
157 WorkList.push_back(Ty);
158 while (!WorkList.empty()) {
159 const Type* Ty = WorkList.back();
160 SeenList.push_back(Ty);
161 WorkList.pop_back();
162 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
163 // Check to see if this is an unresolved type
164 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
165 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
166 for ( ; I != E; ++I) {
167 if (I->second.get() == OpTy)
168 return true;
169 }
170 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
171 const Type* TheTy = SeqTy->getElementType();
172 if (TheTy->isAbstract() && TheTy != Ty) {
173 std::vector<const Type*>::iterator I = SeenList.begin(),
174 E = SeenList.end();
175 for ( ; I != E; ++I)
176 if (*I == TheTy)
177 break;
178 if (I == E)
179 WorkList.push_back(TheTy);
180 }
181 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
182 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
183 const Type* TheTy = StrTy->getElementType(i);
184 if (TheTy->isAbstract() && TheTy != Ty) {
185 std::vector<const Type*>::iterator I = SeenList.begin(),
186 E = SeenList.end();
187 for ( ; I != E; ++I)
188 if (*I == TheTy)
189 break;
190 if (I == E)
191 WorkList.push_back(TheTy);
192 }
193 }
194 }
195 }
196 return false;
197 }
198} CurModule;
199
200static struct PerFunctionInfo {
201 Function *CurrentFunction; // Pointer to current function being created
202
203 ValueList Values; // Keep track of #'d definitions
204 unsigned NextValNum;
205 ValueList LateResolveValues;
206 bool isDeclare; // Is this function a forward declararation?
207 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
208 GlobalValue::VisibilityTypes Visibility;
209
210 /// BBForwardRefs - When we see forward references to basic blocks, keep
211 /// track of them here.
212 std::map<ValID, BasicBlock*> BBForwardRefs;
213
214 inline PerFunctionInfo() {
215 CurrentFunction = 0;
216 isDeclare = false;
217 Linkage = GlobalValue::ExternalLinkage;
218 Visibility = GlobalValue::DefaultVisibility;
219 }
220
221 inline void FunctionStart(Function *M) {
222 CurrentFunction = M;
223 NextValNum = 0;
224 }
225
226 void FunctionDone() {
227 // Any forward referenced blocks left?
228 if (!BBForwardRefs.empty()) {
229 GenerateError("Undefined reference to label " +
230 BBForwardRefs.begin()->second->getName());
231 return;
232 }
233
234 // Resolve all forward references now.
235 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
236
237 Values.clear(); // Clear out function local definitions
238 BBForwardRefs.clear();
239 CurrentFunction = 0;
240 isDeclare = false;
241 Linkage = GlobalValue::ExternalLinkage;
242 Visibility = GlobalValue::DefaultVisibility;
243 }
244} CurFun; // Info for the current function...
245
246static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
247
248
249//===----------------------------------------------------------------------===//
250// Code to handle definitions of all the types
251//===----------------------------------------------------------------------===//
252
253static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
254 // Things that have names or are void typed don't get slot numbers
255 if (V->hasName() || (V->getType() == Type::VoidTy))
256 return;
257
258 // In the case of function values, we have to allow for the forward reference
259 // of basic blocks, which are included in the numbering. Consequently, we keep
260 // track of the next insertion location with NextValNum. When a BB gets
261 // inserted, it could change the size of the CurFun.Values vector.
262 if (&ValueTab == &CurFun.Values) {
263 if (ValueTab.size() <= CurFun.NextValNum)
264 ValueTab.resize(CurFun.NextValNum+1);
265 ValueTab[CurFun.NextValNum++] = V;
266 return;
267 }
268 // For all other lists, its okay to just tack it on the back of the vector.
269 ValueTab.push_back(V);
270}
271
272static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273 switch (D.Type) {
274 case ValID::LocalID: // Is it a numbered definition?
275 // Module constants occupy the lowest numbered slots...
276 if (D.Num < CurModule.Types.size())
277 return CurModule.Types[D.Num];
278 break;
279 case ValID::LocalName: // Is it a named definition?
280 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
281 D.destroy(); // Free old strdup'd memory...
282 return N;
283 }
284 break;
285 default:
286 GenerateError("Internal parser error: Invalid symbol type reference");
287 return 0;
288 }
289
290 // If we reached here, we referenced either a symbol that we don't know about
291 // or an id number that hasn't been read yet. We may be referencing something
292 // forward, so just create an entry to be resolved later and get to it...
293 //
294 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
295
296
297 if (inFunctionScope()) {
298 if (D.Type == ValID::LocalName) {
299 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
300 return 0;
301 } else {
302 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
303 return 0;
304 }
305 }
306
307 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
308 if (I != CurModule.LateResolveTypes.end())
309 return I->second;
310
311 Type *Typ = OpaqueType::get();
312 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
313 return Typ;
314 }
315
316// getExistingVal - Look up the value specified by the provided type and
317// the provided ValID. If the value exists and has already been defined, return
318// it. Otherwise return null.
319//
320static Value *getExistingVal(const Type *Ty, const ValID &D) {
321 if (isa<FunctionType>(Ty)) {
322 GenerateError("Functions are not values and "
323 "must be referenced as pointers");
324 return 0;
325 }
326
327 switch (D.Type) {
328 case ValID::LocalID: { // Is it a numbered definition?
329 // Check that the number is within bounds.
330 if (D.Num >= CurFun.Values.size())
331 return 0;
332 Value *Result = CurFun.Values[D.Num];
333 if (Ty != Result->getType()) {
334 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
335 Result->getType()->getDescription() + "' does not match "
336 "expected type, '" + Ty->getDescription() + "'");
337 return 0;
338 }
339 return Result;
340 }
341 case ValID::GlobalID: { // Is it a numbered definition?
342 if (D.Num >= CurModule.Values.size())
343 return 0;
344 Value *Result = CurModule.Values[D.Num];
345 if (Ty != Result->getType()) {
346 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
347 Result->getType()->getDescription() + "' does not match "
348 "expected type, '" + Ty->getDescription() + "'");
349 return 0;
350 }
351 return Result;
352 }
353
354 case ValID::LocalName: { // Is it a named definition?
355 if (!inFunctionScope())
356 return 0;
357 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
358 Value *N = SymTab.lookup(D.getName());
359 if (N == 0)
360 return 0;
361 if (N->getType() != Ty)
362 return 0;
363
364 D.destroy(); // Free old strdup'd memory...
365 return N;
366 }
367 case ValID::GlobalName: { // Is it a named definition?
368 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
369 Value *N = SymTab.lookup(D.getName());
370 if (N == 0)
371 return 0;
372 if (N->getType() != Ty)
373 return 0;
374
375 D.destroy(); // Free old strdup'd memory...
376 return N;
377 }
378
379 // Check to make sure that "Ty" is an integral type, and that our
380 // value will fit into the specified type...
381 case ValID::ConstSIntVal: // Is it a constant pool reference??
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000382 if (!isa<IntegerType>(Ty) ||
383 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 GenerateError("Signed integral constant '" +
385 itostr(D.ConstPool64) + "' is invalid for type '" +
386 Ty->getDescription() + "'");
387 return 0;
388 }
389 return ConstantInt::get(Ty, D.ConstPool64, true);
390
391 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000392 if (isa<IntegerType>(Ty) &&
393 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 return ConstantInt::get(Ty, D.UConstPool64);
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000395
396 if (!isa<IntegerType>(Ty) ||
397 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
398 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
399 "' is invalid or out of range for type '" +
400 Ty->getDescription() + "'");
401 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 }
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000403 // This is really a signed reference. Transmogrify.
404 return ConstantInt::get(Ty, D.ConstPool64, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405
406 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000407 if (!Ty->isFloatingPoint() ||
408 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 GenerateError("FP constant invalid for type");
410 return 0;
411 }
Dale Johannesen1616e902007-09-11 18:32:33 +0000412 // Lexer has no type info, so builds all float and double FP constants
413 // as double. Fix this here. Long double does not need this.
414 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
415 Ty==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000416 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
417 return ConstantFP::get(Ty, *D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418
419 case ValID::ConstNullVal: // Is it a null value?
420 if (!isa<PointerType>(Ty)) {
421 GenerateError("Cannot create a a non pointer null");
422 return 0;
423 }
424 return ConstantPointerNull::get(cast<PointerType>(Ty));
425
426 case ValID::ConstUndefVal: // Is it an undef value?
427 return UndefValue::get(Ty);
428
429 case ValID::ConstZeroVal: // Is it a zero value?
430 return Constant::getNullValue(Ty);
431
432 case ValID::ConstantVal: // Fully resolved constant?
433 if (D.ConstantValue->getType() != Ty) {
434 GenerateError("Constant expression type different from required type");
435 return 0;
436 }
437 return D.ConstantValue;
438
439 case ValID::InlineAsmVal: { // Inline asm expression
440 const PointerType *PTy = dyn_cast<PointerType>(Ty);
441 const FunctionType *FTy =
442 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
443 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
444 GenerateError("Invalid type for asm constraint string");
445 return 0;
446 }
447 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
448 D.IAD->HasSideEffects);
449 D.destroy(); // Free InlineAsmDescriptor.
450 return IA;
451 }
452 default:
453 assert(0 && "Unhandled case!");
454 return 0;
455 } // End of switch
456
457 assert(0 && "Unhandled case!");
458 return 0;
459}
460
461// getVal - This function is identical to getExistingVal, except that if a
462// value is not already defined, it "improvises" by creating a placeholder var
463// that looks and acts just like the requested variable. When the value is
464// defined later, all uses of the placeholder variable are replaced with the
465// real thing.
466//
467static Value *getVal(const Type *Ty, const ValID &ID) {
468 if (Ty == Type::LabelTy) {
469 GenerateError("Cannot use a basic block here");
470 return 0;
471 }
472
473 // See if the value has already been defined.
474 Value *V = getExistingVal(Ty, ID);
475 if (V) return V;
476 if (TriggerError) return 0;
477
478 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
479 GenerateError("Invalid use of a composite type");
480 return 0;
481 }
482
483 // If we reached here, we referenced either a symbol that we don't know about
484 // or an id number that hasn't been read yet. We may be referencing something
485 // forward, so just create an entry to be resolved later and get to it...
486 //
487 switch (ID.Type) {
488 case ValID::GlobalName:
489 case ValID::GlobalID: {
490 const PointerType *PTy = dyn_cast<PointerType>(Ty);
491 if (!PTy) {
492 GenerateError("Invalid type for reference to global" );
493 return 0;
494 }
495 const Type* ElTy = PTy->getElementType();
496 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
497 V = new Function(FTy, GlobalValue::ExternalLinkage);
498 else
Christopher Lamb44d62f62007-12-11 08:59:05 +0000499 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
500 (Module*)0, false, PTy->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 break;
502 }
503 default:
504 V = new Argument(Ty);
505 }
506
507 // Remember where this forward reference came from. FIXME, shouldn't we try
508 // to recycle these things??
509 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
Chris Lattner17e73c22007-11-18 08:46:26 +0000510 LLLgetLineNo())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511
512 if (inFunctionScope())
513 InsertValue(V, CurFun.LateResolveValues);
514 else
515 InsertValue(V, CurModule.LateResolveValues);
516 return V;
517}
518
519/// defineBBVal - This is a definition of a new basic block with the specified
520/// identifier which must be the same as CurFun.NextValNum, if its numeric.
521static BasicBlock *defineBBVal(const ValID &ID) {
522 assert(inFunctionScope() && "Can't get basic block at global scope!");
523
524 BasicBlock *BB = 0;
525
526 // First, see if this was forward referenced
527
528 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
529 if (BBI != CurFun.BBForwardRefs.end()) {
530 BB = BBI->second;
531 // The forward declaration could have been inserted anywhere in the
532 // function: insert it into the correct place now.
533 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
534 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
535
536 // We're about to erase the entry, save the key so we can clean it up.
537 ValID Tmp = BBI->first;
538
539 // Erase the forward ref from the map as its no longer "forward"
540 CurFun.BBForwardRefs.erase(ID);
541
542 // The key has been removed from the map but so we don't want to leave
543 // strdup'd memory around so destroy it too.
544 Tmp.destroy();
545
546 // If its a numbered definition, bump the number and set the BB value.
547 if (ID.Type == ValID::LocalID) {
548 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
549 InsertValue(BB);
550 }
551
552 ID.destroy();
553 return BB;
554 }
555
556 // We haven't seen this BB before and its first mention is a definition.
557 // Just create it and return it.
558 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
559 BB = new BasicBlock(Name, CurFun.CurrentFunction);
560 if (ID.Type == ValID::LocalID) {
561 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
562 InsertValue(BB);
563 }
564
565 ID.destroy(); // Free strdup'd memory
566 return BB;
567}
568
569/// getBBVal - get an existing BB value or create a forward reference for it.
570///
571static BasicBlock *getBBVal(const ValID &ID) {
572 assert(inFunctionScope() && "Can't get basic block at global scope!");
573
574 BasicBlock *BB = 0;
575
576 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
577 if (BBI != CurFun.BBForwardRefs.end()) {
578 BB = BBI->second;
579 } if (ID.Type == ValID::LocalName) {
580 std::string Name = ID.getName();
581 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000582 if (N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 if (N->getType()->getTypeID() == Type::LabelTyID)
584 BB = cast<BasicBlock>(N);
585 else
586 GenerateError("Reference to label '" + Name + "' is actually of type '"+
587 N->getType()->getDescription() + "'");
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000588 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 } else if (ID.Type == ValID::LocalID) {
590 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
591 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
592 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
593 else
594 GenerateError("Reference to label '%" + utostr(ID.Num) +
595 "' is actually of type '"+
596 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
597 }
598 } else {
599 GenerateError("Illegal label reference " + ID.getName());
600 return 0;
601 }
602
603 // If its already been defined, return it now.
604 if (BB) {
605 ID.destroy(); // Free strdup'd memory.
606 return BB;
607 }
608
609 // Otherwise, this block has not been seen before, create it.
610 std::string Name;
611 if (ID.Type == ValID::LocalName)
612 Name = ID.getName();
613 BB = new BasicBlock(Name, CurFun.CurrentFunction);
614
615 // Insert it in the forward refs map.
616 CurFun.BBForwardRefs[ID] = BB;
617
618 return BB;
619}
620
621
622//===----------------------------------------------------------------------===//
623// Code to handle forward references in instructions
624//===----------------------------------------------------------------------===//
625//
626// This code handles the late binding needed with statements that reference
627// values not defined yet... for example, a forward branch, or the PHI node for
628// a loop body.
629//
630// This keeps a table (CurFun.LateResolveValues) of all such forward references
631// and back patchs after we are done.
632//
633
634// ResolveDefinitions - If we could not resolve some defs at parsing
635// time (forward branches, phi functions for loops, etc...) resolve the
636// defs now...
637//
638static void
639ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
640 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
641 while (!LateResolvers.empty()) {
642 Value *V = LateResolvers.back();
643 LateResolvers.pop_back();
644
645 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
646 CurModule.PlaceHolderInfo.find(V);
647 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
648
649 ValID &DID = PHI->second.first;
650
651 Value *TheRealValue = getExistingVal(V->getType(), DID);
652 if (TriggerError)
653 return;
654 if (TheRealValue) {
655 V->replaceAllUsesWith(TheRealValue);
656 delete V;
657 CurModule.PlaceHolderInfo.erase(PHI);
658 } else if (FutureLateResolvers) {
659 // Functions have their unresolved items forwarded to the module late
660 // resolver table
661 InsertValue(V, *FutureLateResolvers);
662 } else {
663 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
664 GenerateError("Reference to an invalid definition: '" +DID.getName()+
665 "' of type '" + V->getType()->getDescription() + "'",
666 PHI->second.second);
667 return;
668 } else {
669 GenerateError("Reference to an invalid definition: #" +
670 itostr(DID.Num) + " of type '" +
671 V->getType()->getDescription() + "'",
672 PHI->second.second);
673 return;
674 }
675 }
676 }
677 LateResolvers.clear();
678}
679
680// ResolveTypeTo - A brand new type was just declared. This means that (if
681// name is not null) things referencing Name can be resolved. Otherwise, things
682// refering to the number can be resolved. Do this now.
683//
684static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
685 ValID D;
686 if (Name)
687 D = ValID::createLocalName(*Name);
688 else
689 D = ValID::createLocalID(CurModule.Types.size());
690
691 std::map<ValID, PATypeHolder>::iterator I =
692 CurModule.LateResolveTypes.find(D);
693 if (I != CurModule.LateResolveTypes.end()) {
694 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
695 CurModule.LateResolveTypes.erase(I);
696 }
697}
698
699// setValueName - Set the specified value to the name given. The name may be
700// null potentially, in which case this is a noop. The string passed in is
701// assumed to be a malloc'd string buffer, and is free'd by this function.
702//
703static void setValueName(Value *V, std::string *NameStr) {
704 if (!NameStr) return;
705 std::string Name(*NameStr); // Copy string
706 delete NameStr; // Free old string
707
708 if (V->getType() == Type::VoidTy) {
709 GenerateError("Can't assign name '" + Name+"' to value with void type");
710 return;
711 }
712
713 assert(inFunctionScope() && "Must be in function scope!");
714 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
715 if (ST.lookup(Name)) {
716 GenerateError("Redefinition of value '" + Name + "' of type '" +
717 V->getType()->getDescription() + "'");
718 return;
719 }
720
721 // Set the name.
722 V->setName(Name);
723}
724
725/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
726/// this is a declaration, otherwise it is a definition.
727static GlobalVariable *
728ParseGlobalVariable(std::string *NameStr,
729 GlobalValue::LinkageTypes Linkage,
730 GlobalValue::VisibilityTypes Visibility,
731 bool isConstantGlobal, const Type *Ty,
Christopher Lamb44d62f62007-12-11 08:59:05 +0000732 Constant *Initializer, bool IsThreadLocal,
733 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 if (isa<FunctionType>(Ty)) {
735 GenerateError("Cannot declare global vars of function type");
736 return 0;
737 }
738
Christopher Lamb44d62f62007-12-11 08:59:05 +0000739 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740
741 std::string Name;
742 if (NameStr) {
743 Name = *NameStr; // Copy string
744 delete NameStr; // Free old string
745 }
746
747 // See if this global value was forward referenced. If so, recycle the
748 // object.
749 ValID ID;
750 if (!Name.empty()) {
751 ID = ValID::createGlobalName(Name);
752 } else {
753 ID = ValID::createGlobalID(CurModule.Values.size());
754 }
755
756 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
757 // Move the global to the end of the list, from whereever it was
758 // previously inserted.
759 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
760 CurModule.CurrentModule->getGlobalList().remove(GV);
761 CurModule.CurrentModule->getGlobalList().push_back(GV);
762 GV->setInitializer(Initializer);
763 GV->setLinkage(Linkage);
764 GV->setVisibility(Visibility);
765 GV->setConstant(isConstantGlobal);
766 GV->setThreadLocal(IsThreadLocal);
767 InsertValue(GV, CurModule.Values);
768 return GV;
769 }
770
771 // If this global has a name
772 if (!Name.empty()) {
773 // if the global we're parsing has an initializer (is a definition) and
774 // has external linkage.
775 if (Initializer && Linkage != GlobalValue::InternalLinkage)
776 // If there is already a global with external linkage with this name
777 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
778 // If we allow this GVar to get created, it will be renamed in the
779 // symbol table because it conflicts with an existing GVar. We can't
780 // allow redefinition of GVars whose linking indicates that their name
781 // must stay the same. Issue the error.
782 GenerateError("Redefinition of global variable named '" + Name +
783 "' of type '" + Ty->getDescription() + "'");
784 return 0;
785 }
786 }
787
788 // Otherwise there is no existing GV to use, create one now.
789 GlobalVariable *GV =
790 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb44d62f62007-12-11 08:59:05 +0000791 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 GV->setVisibility(Visibility);
793 InsertValue(GV, CurModule.Values);
794 return GV;
795}
796
797// setTypeName - Set the specified type to the name given. The name may be
798// null potentially, in which case this is a noop. The string passed in is
799// assumed to be a malloc'd string buffer, and is freed by this function.
800//
801// This function returns true if the type has already been defined, but is
802// allowed to be redefined in the specified context. If the name is a new name
803// for the type plane, it is inserted and false is returned.
804static bool setTypeName(const Type *T, std::string *NameStr) {
805 assert(!inFunctionScope() && "Can't give types function-local names!");
806 if (NameStr == 0) return false;
807
808 std::string Name(*NameStr); // Copy string
809 delete NameStr; // Free old string
810
811 // We don't allow assigning names to void type
812 if (T == Type::VoidTy) {
813 GenerateError("Can't assign name '" + Name + "' to the void type");
814 return false;
815 }
816
817 // Set the type name, checking for conflicts as we do so.
818 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
819
820 if (AlreadyExists) { // Inserting a name that is already defined???
821 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
822 assert(Existing && "Conflict but no matching type?!");
823
824 // There is only one case where this is allowed: when we are refining an
825 // opaque type. In this case, Existing will be an opaque type.
826 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
827 // We ARE replacing an opaque type!
828 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
829 return true;
830 }
831
832 // Otherwise, this is an attempt to redefine a type. That's okay if
833 // the redefinition is identical to the original. This will be so if
834 // Existing and T point to the same Type object. In this one case we
835 // allow the equivalent redefinition.
836 if (Existing == T) return true; // Yes, it's equal.
837
838 // Any other kind of (non-equivalent) redefinition is an error.
839 GenerateError("Redefinition of type named '" + Name + "' of type '" +
840 T->getDescription() + "'");
841 }
842
843 return false;
844}
845
846//===----------------------------------------------------------------------===//
847// Code for handling upreferences in type names...
848//
849
850// TypeContains - Returns true if Ty directly contains E in it.
851//
852static bool TypeContains(const Type *Ty, const Type *E) {
853 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
854 E) != Ty->subtype_end();
855}
856
857namespace {
858 struct UpRefRecord {
859 // NestingLevel - The number of nesting levels that need to be popped before
860 // this type is resolved.
861 unsigned NestingLevel;
862
863 // LastContainedTy - This is the type at the current binding level for the
864 // type. Every time we reduce the nesting level, this gets updated.
865 const Type *LastContainedTy;
866
867 // UpRefTy - This is the actual opaque type that the upreference is
868 // represented with.
869 OpaqueType *UpRefTy;
870
871 UpRefRecord(unsigned NL, OpaqueType *URTy)
872 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
873 };
874}
875
876// UpRefs - A list of the outstanding upreferences that need to be resolved.
877static std::vector<UpRefRecord> UpRefs;
878
879/// HandleUpRefs - Every time we finish a new layer of types, this function is
880/// called. It loops through the UpRefs vector, which is a list of the
881/// currently active types. For each type, if the up reference is contained in
882/// the newly completed type, we decrement the level count. When the level
883/// count reaches zero, the upreferenced type is the type that is passed in:
884/// thus we can complete the cycle.
885///
886static PATypeHolder HandleUpRefs(const Type *ty) {
887 // If Ty isn't abstract, or if there are no up-references in it, then there is
888 // nothing to resolve here.
889 if (!ty->isAbstract() || UpRefs.empty()) return ty;
890
891 PATypeHolder Ty(ty);
892 UR_OUT("Type '" << Ty->getDescription() <<
893 "' newly formed. Resolving upreferences.\n" <<
894 UpRefs.size() << " upreferences active!\n");
895
896 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
897 // to zero), we resolve them all together before we resolve them to Ty. At
898 // the end of the loop, if there is anything to resolve to Ty, it will be in
899 // this variable.
900 OpaqueType *TypeToResolve = 0;
901
902 for (unsigned i = 0; i != UpRefs.size(); ++i) {
903 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
904 << UpRefs[i].second->getDescription() << ") = "
905 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
906 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
907 // Decrement level of upreference
908 unsigned Level = --UpRefs[i].NestingLevel;
909 UpRefs[i].LastContainedTy = Ty;
910 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
911 if (Level == 0) { // Upreference should be resolved!
912 if (!TypeToResolve) {
913 TypeToResolve = UpRefs[i].UpRefTy;
914 } else {
915 UR_OUT(" * Resolving upreference for "
916 << UpRefs[i].second->getDescription() << "\n";
917 std::string OldName = UpRefs[i].UpRefTy->getDescription());
918 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
919 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
920 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
921 }
922 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
923 --i; // Do not skip the next element...
924 }
925 }
926 }
927
928 if (TypeToResolve) {
929 UR_OUT(" * Resolving upreference for "
930 << UpRefs[i].second->getDescription() << "\n";
931 std::string OldName = TypeToResolve->getDescription());
932 TypeToResolve->refineAbstractTypeTo(Ty);
933 }
934
935 return Ty;
936}
937
938//===----------------------------------------------------------------------===//
939// RunVMAsmParser - Define an interface to this parser
940//===----------------------------------------------------------------------===//
941//
942static Module* RunParser(Module * M);
943
Chris Lattner17e73c22007-11-18 08:46:26 +0000944Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
945 InitLLLexer(MB);
946 Module *M = RunParser(new Module(LLLgetFilename()));
947 FreeLexer();
948 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949}
950
951%}
952
953%union {
954 llvm::Module *ModuleVal;
955 llvm::Function *FunctionVal;
956 llvm::BasicBlock *BasicBlockVal;
957 llvm::TerminatorInst *TermInstVal;
958 llvm::Instruction *InstVal;
959 llvm::Constant *ConstVal;
960
961 const llvm::Type *PrimType;
962 std::list<llvm::PATypeHolder> *TypeList;
963 llvm::PATypeHolder *TypeVal;
964 llvm::Value *ValueVal;
965 std::vector<llvm::Value*> *ValueList;
966 llvm::ArgListType *ArgList;
967 llvm::TypeWithAttrs TypeWithAttrs;
968 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000969 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970
971 // Represent the RHS of PHI node
972 std::list<std::pair<llvm::Value*,
973 llvm::BasicBlock*> > *PHIList;
974 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
975 std::vector<llvm::Constant*> *ConstVector;
976
977 llvm::GlobalValue::LinkageTypes Linkage;
978 llvm::GlobalValue::VisibilityTypes Visibility;
Dale Johannesenf4666f52008-02-19 21:38:47 +0000979 llvm::ParameterAttributes ParamAttrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 llvm::APInt *APIntVal;
981 int64_t SInt64Val;
982 uint64_t UInt64Val;
983 int SIntVal;
984 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000985 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 bool BoolVal;
987
988 std::string *StrVal; // This memory must be deleted
989 llvm::ValID ValIDVal;
990
991 llvm::Instruction::BinaryOps BinaryOpVal;
992 llvm::Instruction::TermOps TermOpVal;
993 llvm::Instruction::MemoryOps MemOpVal;
994 llvm::Instruction::CastOps CastOpVal;
995 llvm::Instruction::OtherOps OtherOpVal;
996 llvm::ICmpInst::Predicate IPredicate;
997 llvm::FCmpInst::Predicate FPredicate;
998}
999
1000%type <ModuleVal> Module
1001%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1002%type <BasicBlockVal> BasicBlock InstructionList
1003%type <TermInstVal> BBTerminatorInst
1004%type <InstVal> Inst InstVal MemoryInst
1005%type <ConstVal> ConstVal ConstExpr AliaseeRef
1006%type <ConstVector> ConstVector
1007%type <ArgList> ArgList ArgListH
1008%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001009%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010%type <ValueList> IndexList // For GEP indices
1011%type <TypeList> TypeListI
1012%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1013%type <TypeWithAttrs> ArgType
1014%type <JumpTable> JumpTable
1015%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1016%type <BoolVal> ThreadLocal // 'thread_local' or not
1017%type <BoolVal> OptVolatile // 'volatile' or not
1018%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1019%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1020%type <Linkage> GVInternalLinkage GVExternalLinkage
1021%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1022%type <Linkage> AliasLinkage
1023%type <Visibility> GVVisibilityStyle
1024
1025// ValueRef - Unresolved reference to a definition or BB
1026%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1027%type <ValueVal> ResolvedVal // <type> <valref> pair
Devang Patel036f0382008-02-20 22:39:45 +00001028%type <ValueList> ReturnedVal
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029// Tokens and types for handling constant integer values
1030//
1031// ESINT64VAL - A negative number within long long range
1032%token <SInt64Val> ESINT64VAL
1033
1034// EUINT64VAL - A positive number within uns. long long range
1035%token <UInt64Val> EUINT64VAL
1036
1037// ESAPINTVAL - A negative number with arbitrary precision
1038%token <APIntVal> ESAPINTVAL
1039
1040// EUAPINTVAL - A positive number with arbitrary precision
1041%token <APIntVal> EUAPINTVAL
1042
1043%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1044%token <FPVal> FPVAL // Float or Double constant
1045
1046// Built in types...
1047%type <TypeVal> Types ResultTypes
1048%type <PrimType> IntType FPType PrimType // Classifications
1049%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001050%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051%token TYPE
1052
1053
1054%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1055%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1056%type <StrVal> LocalName OptLocalName OptLocalAssign
1057%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001058%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059
Christopher Lamb20a39e92007-12-12 08:44:39 +00001060%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061
1062%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1063%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1064%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1065%token DLLIMPORT DLLEXPORT EXTERN_WEAK
Christopher Lamb44d62f62007-12-11 08:59:05 +00001066%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1068%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1069%token DATALAYOUT
1070%type <UIntVal> OptCallingConv
1071%type <ParamAttrs> OptParamAttrs ParamAttr
1072%type <ParamAttrs> OptFuncAttrs FuncAttr
1073
1074// Basic Block Terminating Operators
1075%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1076
1077// Binary Operators
1078%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1079%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1080%token <BinaryOpVal> SHL LSHR ASHR
1081
1082%token <OtherOpVal> ICMP FCMP
1083%type <IPredicate> IPredicates
1084%type <FPredicate> FPredicates
1085%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1086%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1087
1088// Memory Instructions
1089%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1090
1091// Cast Operators
1092%type <CastOpVal> CastOps
1093%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1094%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1095
1096// Other Operators
1097%token <OtherOpVal> PHI_TOK SELECT VAARG
1098%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Devang Patele5c806a2008-02-19 22:26:37 +00001099%token <OtherOpVal> GETRESULT
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100
1101// Function Attributes
Duncan Sands38947cd2007-07-27 12:58:54 +00001102%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001103%token READNONE READONLY GC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104
1105// Visibility Styles
1106%token DEFAULT HIDDEN PROTECTED
1107
1108%start Module
1109%%
1110
1111
1112// Operations that are notably excluded from this list include:
1113// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1114//
1115ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1116LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1117CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1118 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1119
1120IPredicates
1121 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1122 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1123 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1124 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1125 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1126 ;
1127
1128FPredicates
1129 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1130 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1131 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1132 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1133 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1134 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1135 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1136 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1137 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1138 ;
1139
1140// These are some types that allow classification if we only want a particular
1141// thing... for example, only a signed, unsigned, or integral type.
1142IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001143FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144
1145LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1146OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1147
Christopher Lamb20a39e92007-12-12 08:44:39 +00001148OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1149 | /*empty*/ { $$=0; };
1150
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151/// OptLocalAssign - Value producing statements have an optional assignment
1152/// component.
1153OptLocalAssign : LocalName '=' {
1154 $$ = $1;
1155 CHECK_FOR_ERROR
1156 }
1157 | /*empty*/ {
1158 $$ = 0;
1159 CHECK_FOR_ERROR
1160 };
1161
1162GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1163
1164OptGlobalAssign : GlobalAssign
1165 | /*empty*/ {
1166 $$ = 0;
1167 CHECK_FOR_ERROR
1168 };
1169
1170GlobalAssign : GlobalName '=' {
1171 $$ = $1;
1172 CHECK_FOR_ERROR
1173 };
1174
1175GVInternalLinkage
1176 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1177 | WEAK { $$ = GlobalValue::WeakLinkage; }
1178 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1179 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1180 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1181 ;
1182
1183GVExternalLinkage
1184 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1185 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1186 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1187 ;
1188
1189GVVisibilityStyle
1190 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1191 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1192 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1193 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1194 ;
1195
1196FunctionDeclareLinkage
1197 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1198 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1199 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1200 ;
1201
1202FunctionDefineLinkage
1203 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1204 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1205 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1206 | WEAK { $$ = GlobalValue::WeakLinkage; }
1207 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1208 ;
1209
1210AliasLinkage
1211 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1212 | WEAK { $$ = GlobalValue::WeakLinkage; }
1213 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1214 ;
1215
1216OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1217 CCC_TOK { $$ = CallingConv::C; } |
1218 FASTCC_TOK { $$ = CallingConv::Fast; } |
1219 COLDCC_TOK { $$ = CallingConv::Cold; } |
1220 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1221 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1222 CC_TOK EUINT64VAL {
1223 if ((unsigned)$2 != $2)
1224 GEN_ERROR("Calling conv too large");
1225 $$ = $2;
1226 CHECK_FOR_ERROR
1227 };
1228
Reid Spencerf234bed2007-07-19 23:13:04 +00001229ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001230 | ZEXT { $$ = ParamAttr::ZExt; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001231 | SIGNEXT { $$ = ParamAttr::SExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001232 | SEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 | INREG { $$ = ParamAttr::InReg; }
1234 | SRET { $$ = ParamAttr::StructRet; }
1235 | NOALIAS { $$ = ParamAttr::NoAlias; }
Duncan Sands38947cd2007-07-27 12:58:54 +00001236 | BYVAL { $$ = ParamAttr::ByVal; }
1237 | NEST { $$ = ParamAttr::Nest; }
Dale Johannesen9b398782008-02-22 17:49:45 +00001238 | ALIGN EUINT64VAL { $$ =
1239 ParamAttr::constructAlignmentFromInt($2); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 ;
1241
1242OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1243 | OptParamAttrs ParamAttr {
1244 $$ = $1 | $2;
1245 }
1246 ;
1247
1248FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1249 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001250 | ZEROEXT { $$ = ParamAttr::ZExt; }
1251 | SIGNEXT { $$ = ParamAttr::SExt; }
Duncan Sands13e13f82007-11-22 20:23:04 +00001252 | READNONE { $$ = ParamAttr::ReadNone; }
1253 | READONLY { $$ = ParamAttr::ReadOnly; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 ;
1255
1256OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1257 | OptFuncAttrs FuncAttr {
1258 $$ = $1 | $2;
1259 }
1260 ;
1261
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001262OptGC : /* empty */ { $$ = 0; }
1263 | GC STRINGCONSTANT {
1264 $$ = $2;
1265 }
1266 ;
1267
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1269// a comma before it.
1270OptAlign : /*empty*/ { $$ = 0; } |
1271 ALIGN EUINT64VAL {
1272 $$ = $2;
1273 if ($$ != 0 && !isPowerOf2_32($$))
1274 GEN_ERROR("Alignment must be a power of two");
1275 CHECK_FOR_ERROR
1276};
1277OptCAlign : /*empty*/ { $$ = 0; } |
1278 ',' ALIGN EUINT64VAL {
1279 $$ = $3;
1280 if ($$ != 0 && !isPowerOf2_32($$))
1281 GEN_ERROR("Alignment must be a power of two");
1282 CHECK_FOR_ERROR
1283};
1284
1285
Christopher Lamb44d62f62007-12-11 08:59:05 +00001286
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287SectionString : SECTION STRINGCONSTANT {
1288 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1289 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1290 GEN_ERROR("Invalid character in section name");
1291 $$ = $2;
1292 CHECK_FOR_ERROR
1293};
1294
1295OptSection : /*empty*/ { $$ = 0; } |
1296 SectionString { $$ = $1; };
1297
1298// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1299// is set to be the global we are processing.
1300//
1301GlobalVarAttributes : /* empty */ {} |
1302 ',' GlobalVarAttribute GlobalVarAttributes {};
1303GlobalVarAttribute : SectionString {
1304 CurGV->setSection(*$1);
1305 delete $1;
1306 CHECK_FOR_ERROR
1307 }
1308 | ALIGN EUINT64VAL {
1309 if ($2 != 0 && !isPowerOf2_32($2))
1310 GEN_ERROR("Alignment must be a power of two");
1311 CurGV->setAlignment($2);
1312 CHECK_FOR_ERROR
1313 };
1314
1315//===----------------------------------------------------------------------===//
1316// Types includes all predefined types... except void, because it can only be
1317// used in specific contexts (function returning void for example).
1318
1319// Derived types are added later...
1320//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001321PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322
1323Types
1324 : OPAQUE {
1325 $$ = new PATypeHolder(OpaqueType::get());
1326 CHECK_FOR_ERROR
1327 }
1328 | PrimType {
1329 $$ = new PATypeHolder($1);
1330 CHECK_FOR_ERROR
1331 }
Christopher Lamb20a39e92007-12-12 08:44:39 +00001332 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 if (*$1 == Type::LabelTy)
1334 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb20a39e92007-12-12 08:44:39 +00001335 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb44d62f62007-12-11 08:59:05 +00001336 delete $1;
1337 CHECK_FOR_ERROR
1338 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 | SymbolicValueRef { // Named types are also simple types...
1340 const Type* tmp = getTypeVal($1);
1341 CHECK_FOR_ERROR
1342 $$ = new PATypeHolder(tmp);
1343 }
1344 | '\\' EUINT64VAL { // Type UpReference
1345 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1346 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1347 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1348 $$ = new PATypeHolder(OT);
1349 UR_OUT("New Upreference!\n");
1350 CHECK_FOR_ERROR
1351 }
1352 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001353 // Allow but ignore attributes on function types; this permits auto-upgrade.
1354 // FIXME: remove in LLVM 3.0.
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001355 const Type* RetTy = *$1;
Anton Korobeynikov9ab58082007-12-03 21:00:45 +00001356 if (!(RetTy->isFirstClassType() || RetTy == Type::VoidTy ||
1357 isa<OpaqueType>(RetTy)))
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001358 GEN_ERROR("LLVM Functions cannot return aggregates");
1359
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001362 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 const Type *Ty = I->Ty->get();
1364 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001366
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1368 if (isVarArg) Params.pop_back();
1369
Anton Korobeynikov9ab58082007-12-03 21:00:45 +00001370 for (unsigned i = 0; i != Params.size(); ++i)
1371 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1372 GEN_ERROR("Function arguments must be value types!");
1373
1374 CHECK_FOR_ERROR
1375
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001376 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001377 delete $3; // Delete the argument list
1378 delete $1; // Delete the return type handle
1379 $$ = new PATypeHolder(HandleUpRefs(FT));
1380 CHECK_FOR_ERROR
1381 }
1382 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001383 // Allow but ignore attributes on function types; this permits auto-upgrade.
1384 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001387 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 const Type* Ty = I->Ty->get();
1389 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001391
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1393 if (isVarArg) Params.pop_back();
1394
Anton Korobeynikov9ab58082007-12-03 21:00:45 +00001395 for (unsigned i = 0; i != Params.size(); ++i)
1396 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1397 GEN_ERROR("Function arguments must be value types!");
1398
1399 CHECK_FOR_ERROR
1400
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001401 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 delete $3; // Delete the argument list
1403 $$ = new PATypeHolder(HandleUpRefs(FT));
1404 CHECK_FOR_ERROR
1405 }
1406
1407 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1408 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1409 delete $4;
1410 CHECK_FOR_ERROR
1411 }
1412 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1413 const llvm::Type* ElemTy = $4->get();
1414 if ((unsigned)$2 != $2)
1415 GEN_ERROR("Unsigned result not equal to signed result");
1416 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1417 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1419 delete $4;
1420 CHECK_FOR_ERROR
1421 }
1422 | '{' TypeListI '}' { // Structure type?
1423 std::vector<const Type*> Elements;
1424 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1425 E = $2->end(); I != E; ++I)
1426 Elements.push_back(*I);
1427
1428 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1429 delete $2;
1430 CHECK_FOR_ERROR
1431 }
1432 | '{' '}' { // Empty structure type?
1433 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1434 CHECK_FOR_ERROR
1435 }
1436 | '<' '{' TypeListI '}' '>' {
1437 std::vector<const Type*> Elements;
1438 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1439 E = $3->end(); I != E; ++I)
1440 Elements.push_back(*I);
1441
1442 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1443 delete $3;
1444 CHECK_FOR_ERROR
1445 }
1446 | '<' '{' '}' '>' { // Empty structure type?
1447 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1448 CHECK_FOR_ERROR
1449 }
1450 ;
1451
1452ArgType
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001453 : Types OptParamAttrs {
1454 // Allow but ignore attributes on function types; this permits auto-upgrade.
1455 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 $$.Ty = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001457 $$.Attrs = ParamAttr::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 }
1459 ;
1460
1461ResultTypes
1462 : Types {
1463 if (!UpRefs.empty())
1464 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Devang Patel62417142008-02-23 01:17:17 +00001465 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001466 GEN_ERROR("LLVM functions cannot return aggregate types");
1467 $$ = $1;
1468 }
1469 | VOID {
1470 $$ = new PATypeHolder(Type::VoidTy);
1471 }
1472 ;
1473
1474ArgTypeList : ArgType {
1475 $$ = new TypeWithAttrsList();
1476 $$->push_back($1);
1477 CHECK_FOR_ERROR
1478 }
1479 | ArgTypeList ',' ArgType {
1480 ($$=$1)->push_back($3);
1481 CHECK_FOR_ERROR
1482 }
1483 ;
1484
1485ArgTypeListI
1486 : ArgTypeList
1487 | ArgTypeList ',' DOTDOTDOT {
1488 $$=$1;
1489 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1490 TWA.Ty = new PATypeHolder(Type::VoidTy);
1491 $$->push_back(TWA);
1492 CHECK_FOR_ERROR
1493 }
1494 | DOTDOTDOT {
1495 $$ = new TypeWithAttrsList;
1496 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1497 TWA.Ty = new PATypeHolder(Type::VoidTy);
1498 $$->push_back(TWA);
1499 CHECK_FOR_ERROR
1500 }
1501 | /*empty*/ {
1502 $$ = new TypeWithAttrsList();
1503 CHECK_FOR_ERROR
1504 };
1505
1506// TypeList - Used for struct declarations and as a basis for function type
1507// declaration type lists
1508//
1509TypeListI : Types {
1510 $$ = new std::list<PATypeHolder>();
1511 $$->push_back(*$1);
1512 delete $1;
1513 CHECK_FOR_ERROR
1514 }
1515 | TypeListI ',' Types {
1516 ($$=$1)->push_back(*$3);
1517 delete $3;
1518 CHECK_FOR_ERROR
1519 };
1520
1521// ConstVal - The various declarations that go into the constant pool. This
1522// production is used ONLY to represent constants that show up AFTER a 'const',
1523// 'constant' or 'global' token at global scope. Constants that can be inlined
1524// into other expressions (such as integers and constexprs) are handled by the
1525// ResolvedVal, ValueRef and ConstValueRef productions.
1526//
1527ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1528 if (!UpRefs.empty())
1529 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1530 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1531 if (ATy == 0)
1532 GEN_ERROR("Cannot make array constant with type: '" +
1533 (*$1)->getDescription() + "'");
1534 const Type *ETy = ATy->getElementType();
1535 int NumElements = ATy->getNumElements();
1536
1537 // Verify that we have the correct size...
1538 if (NumElements != -1 && NumElements != (int)$3->size())
1539 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1540 utostr($3->size()) + " arguments, but has size of " +
1541 itostr(NumElements) + "");
1542
1543 // Verify all elements are correct type!
1544 for (unsigned i = 0; i < $3->size(); i++) {
1545 if (ETy != (*$3)[i]->getType())
1546 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1547 ETy->getDescription() +"' as required!\nIt is of type '"+
1548 (*$3)[i]->getType()->getDescription() + "'.");
1549 }
1550
1551 $$ = ConstantArray::get(ATy, *$3);
1552 delete $1; delete $3;
1553 CHECK_FOR_ERROR
1554 }
1555 | Types '[' ']' {
1556 if (!UpRefs.empty())
1557 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1558 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1559 if (ATy == 0)
1560 GEN_ERROR("Cannot make array constant with type: '" +
1561 (*$1)->getDescription() + "'");
1562
1563 int NumElements = ATy->getNumElements();
1564 if (NumElements != -1 && NumElements != 0)
1565 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1566 " arguments, but has size of " + itostr(NumElements) +"");
1567 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1568 delete $1;
1569 CHECK_FOR_ERROR
1570 }
1571 | Types 'c' STRINGCONSTANT {
1572 if (!UpRefs.empty())
1573 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1574 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1575 if (ATy == 0)
1576 GEN_ERROR("Cannot make array constant with type: '" +
1577 (*$1)->getDescription() + "'");
1578
1579 int NumElements = ATy->getNumElements();
1580 const Type *ETy = ATy->getElementType();
1581 if (NumElements != -1 && NumElements != int($3->length()))
1582 GEN_ERROR("Can't build string constant of size " +
1583 itostr((int)($3->length())) +
1584 " when array has size " + itostr(NumElements) + "");
1585 std::vector<Constant*> Vals;
1586 if (ETy == Type::Int8Ty) {
1587 for (unsigned i = 0; i < $3->length(); ++i)
1588 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1589 } else {
1590 delete $3;
1591 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1592 }
1593 delete $3;
1594 $$ = ConstantArray::get(ATy, Vals);
1595 delete $1;
1596 CHECK_FOR_ERROR
1597 }
1598 | Types '<' ConstVector '>' { // Nonempty unsized arr
1599 if (!UpRefs.empty())
1600 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1601 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1602 if (PTy == 0)
1603 GEN_ERROR("Cannot make packed constant with type: '" +
1604 (*$1)->getDescription() + "'");
1605 const Type *ETy = PTy->getElementType();
1606 int NumElements = PTy->getNumElements();
1607
1608 // Verify that we have the correct size...
1609 if (NumElements != -1 && NumElements != (int)$3->size())
1610 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1611 utostr($3->size()) + " arguments, but has size of " +
1612 itostr(NumElements) + "");
1613
1614 // Verify all elements are correct type!
1615 for (unsigned i = 0; i < $3->size(); i++) {
1616 if (ETy != (*$3)[i]->getType())
1617 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1618 ETy->getDescription() +"' as required!\nIt is of type '"+
1619 (*$3)[i]->getType()->getDescription() + "'.");
1620 }
1621
1622 $$ = ConstantVector::get(PTy, *$3);
1623 delete $1; delete $3;
1624 CHECK_FOR_ERROR
1625 }
1626 | Types '{' ConstVector '}' {
1627 const StructType *STy = dyn_cast<StructType>($1->get());
1628 if (STy == 0)
1629 GEN_ERROR("Cannot make struct constant with type: '" +
1630 (*$1)->getDescription() + "'");
1631
1632 if ($3->size() != STy->getNumContainedTypes())
1633 GEN_ERROR("Illegal number of initializers for structure type");
1634
1635 // Check to ensure that constants are compatible with the type initializer!
1636 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1637 if ((*$3)[i]->getType() != STy->getElementType(i))
1638 GEN_ERROR("Expected type '" +
1639 STy->getElementType(i)->getDescription() +
1640 "' for element #" + utostr(i) +
1641 " of structure initializer");
1642
1643 // Check to ensure that Type is not packed
1644 if (STy->isPacked())
1645 GEN_ERROR("Unpacked Initializer to vector type '" +
1646 STy->getDescription() + "'");
1647
1648 $$ = ConstantStruct::get(STy, *$3);
1649 delete $1; delete $3;
1650 CHECK_FOR_ERROR
1651 }
1652 | Types '{' '}' {
1653 if (!UpRefs.empty())
1654 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1655 const StructType *STy = dyn_cast<StructType>($1->get());
1656 if (STy == 0)
1657 GEN_ERROR("Cannot make struct constant with type: '" +
1658 (*$1)->getDescription() + "'");
1659
1660 if (STy->getNumContainedTypes() != 0)
1661 GEN_ERROR("Illegal number of initializers for structure type");
1662
1663 // Check to ensure that Type is not packed
1664 if (STy->isPacked())
1665 GEN_ERROR("Unpacked Initializer to vector type '" +
1666 STy->getDescription() + "'");
1667
1668 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1669 delete $1;
1670 CHECK_FOR_ERROR
1671 }
1672 | Types '<' '{' ConstVector '}' '>' {
1673 const StructType *STy = dyn_cast<StructType>($1->get());
1674 if (STy == 0)
1675 GEN_ERROR("Cannot make struct constant with type: '" +
1676 (*$1)->getDescription() + "'");
1677
1678 if ($4->size() != STy->getNumContainedTypes())
1679 GEN_ERROR("Illegal number of initializers for structure type");
1680
1681 // Check to ensure that constants are compatible with the type initializer!
1682 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1683 if ((*$4)[i]->getType() != STy->getElementType(i))
1684 GEN_ERROR("Expected type '" +
1685 STy->getElementType(i)->getDescription() +
1686 "' for element #" + utostr(i) +
1687 " of structure initializer");
1688
1689 // Check to ensure that Type is packed
1690 if (!STy->isPacked())
1691 GEN_ERROR("Vector initializer to non-vector type '" +
1692 STy->getDescription() + "'");
1693
1694 $$ = ConstantStruct::get(STy, *$4);
1695 delete $1; delete $4;
1696 CHECK_FOR_ERROR
1697 }
1698 | Types '<' '{' '}' '>' {
1699 if (!UpRefs.empty())
1700 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1701 const StructType *STy = dyn_cast<StructType>($1->get());
1702 if (STy == 0)
1703 GEN_ERROR("Cannot make struct constant with type: '" +
1704 (*$1)->getDescription() + "'");
1705
1706 if (STy->getNumContainedTypes() != 0)
1707 GEN_ERROR("Illegal number of initializers for structure type");
1708
1709 // Check to ensure that Type is packed
1710 if (!STy->isPacked())
1711 GEN_ERROR("Vector initializer to non-vector type '" +
1712 STy->getDescription() + "'");
1713
1714 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1715 delete $1;
1716 CHECK_FOR_ERROR
1717 }
1718 | Types NULL_TOK {
1719 if (!UpRefs.empty())
1720 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1721 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1722 if (PTy == 0)
1723 GEN_ERROR("Cannot make null pointer constant with type: '" +
1724 (*$1)->getDescription() + "'");
1725
1726 $$ = ConstantPointerNull::get(PTy);
1727 delete $1;
1728 CHECK_FOR_ERROR
1729 }
1730 | Types UNDEF {
1731 if (!UpRefs.empty())
1732 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1733 $$ = UndefValue::get($1->get());
1734 delete $1;
1735 CHECK_FOR_ERROR
1736 }
1737 | Types SymbolicValueRef {
1738 if (!UpRefs.empty())
1739 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1740 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1741 if (Ty == 0)
Devang Patele5c806a2008-02-19 22:26:37 +00001742 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001743
1744 // ConstExprs can exist in the body of a function, thus creating
1745 // GlobalValues whenever they refer to a variable. Because we are in
1746 // the context of a function, getExistingVal will search the functions
1747 // symbol table instead of the module symbol table for the global symbol,
1748 // which throws things all off. To get around this, we just tell
1749 // getExistingVal that we are at global scope here.
1750 //
1751 Function *SavedCurFn = CurFun.CurrentFunction;
1752 CurFun.CurrentFunction = 0;
1753
1754 Value *V = getExistingVal(Ty, $2);
1755 CHECK_FOR_ERROR
1756
1757 CurFun.CurrentFunction = SavedCurFn;
1758
1759 // If this is an initializer for a constant pointer, which is referencing a
1760 // (currently) undefined variable, create a stub now that shall be replaced
1761 // in the future with the right type of variable.
1762 //
1763 if (V == 0) {
1764 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1765 const PointerType *PT = cast<PointerType>(Ty);
1766
1767 // First check to see if the forward references value is already created!
1768 PerModuleInfo::GlobalRefsType::iterator I =
1769 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1770
1771 if (I != CurModule.GlobalRefs.end()) {
1772 V = I->second; // Placeholder already exists, use it...
1773 $2.destroy();
1774 } else {
1775 std::string Name;
1776 if ($2.Type == ValID::GlobalName)
1777 Name = $2.getName();
1778 else if ($2.Type != ValID::GlobalID)
1779 GEN_ERROR("Invalid reference to global");
1780
1781 // Create the forward referenced global.
1782 GlobalValue *GV;
1783 if (const FunctionType *FTy =
1784 dyn_cast<FunctionType>(PT->getElementType())) {
1785 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1786 CurModule.CurrentModule);
1787 } else {
1788 GV = new GlobalVariable(PT->getElementType(), false,
1789 GlobalValue::ExternalWeakLinkage, 0,
1790 Name, CurModule.CurrentModule);
1791 }
1792
1793 // Keep track of the fact that we have a forward ref to recycle it
1794 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1795 V = GV;
1796 }
1797 }
1798
1799 $$ = cast<GlobalValue>(V);
1800 delete $1; // Free the type handle
1801 CHECK_FOR_ERROR
1802 }
1803 | Types ConstExpr {
1804 if (!UpRefs.empty())
1805 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1806 if ($1->get() != $2->getType())
1807 GEN_ERROR("Mismatched types for constant expression: " +
1808 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1809 $$ = $2;
1810 delete $1;
1811 CHECK_FOR_ERROR
1812 }
1813 | Types ZEROINITIALIZER {
1814 if (!UpRefs.empty())
1815 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1816 const Type *Ty = $1->get();
1817 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1818 GEN_ERROR("Cannot create a null initialized value of this type");
1819 $$ = Constant::getNullValue(Ty);
1820 delete $1;
1821 CHECK_FOR_ERROR
1822 }
1823 | IntType ESINT64VAL { // integral constants
1824 if (!ConstantInt::isValueValidForType($1, $2))
1825 GEN_ERROR("Constant value doesn't fit in type");
1826 $$ = ConstantInt::get($1, $2, true);
1827 CHECK_FOR_ERROR
1828 }
1829 | IntType ESAPINTVAL { // arbitrary precision integer constants
1830 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1831 if ($2->getBitWidth() > BitWidth) {
1832 GEN_ERROR("Constant value does not fit in type");
1833 }
1834 $2->sextOrTrunc(BitWidth);
1835 $$ = ConstantInt::get(*$2);
1836 delete $2;
1837 CHECK_FOR_ERROR
1838 }
1839 | IntType EUINT64VAL { // integral constants
1840 if (!ConstantInt::isValueValidForType($1, $2))
1841 GEN_ERROR("Constant value doesn't fit in type");
1842 $$ = ConstantInt::get($1, $2, false);
1843 CHECK_FOR_ERROR
1844 }
1845 | IntType EUAPINTVAL { // arbitrary precision integer constants
1846 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1847 if ($2->getBitWidth() > BitWidth) {
1848 GEN_ERROR("Constant value does not fit in type");
1849 }
1850 $2->zextOrTrunc(BitWidth);
1851 $$ = ConstantInt::get(*$2);
1852 delete $2;
1853 CHECK_FOR_ERROR
1854 }
1855 | INTTYPE TRUETOK { // Boolean constants
1856 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1857 $$ = ConstantInt::getTrue();
1858 CHECK_FOR_ERROR
1859 }
1860 | INTTYPE FALSETOK { // Boolean constants
1861 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1862 $$ = ConstantInt::getFalse();
1863 CHECK_FOR_ERROR
1864 }
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00001865 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001866 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen1616e902007-09-11 18:32:33 +00001868 // Lexer has no type info, so builds all float and double FP constants
1869 // as double. Fix this here. Long double is done right.
1870 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001871 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1872 $$ = ConstantFP::get($1, *$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001873 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874 CHECK_FOR_ERROR
1875 };
1876
1877
1878ConstExpr: CastOps '(' ConstVal TO Types ')' {
1879 if (!UpRefs.empty())
1880 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1881 Constant *Val = $3;
1882 const Type *DestTy = $5->get();
1883 if (!CastInst::castIsValid($1, $3, DestTy))
1884 GEN_ERROR("invalid cast opcode for cast from '" +
1885 Val->getType()->getDescription() + "' to '" +
1886 DestTy->getDescription() + "'");
1887 $$ = ConstantExpr::getCast($1, $3, DestTy);
1888 delete $5;
1889 }
1890 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1891 if (!isa<PointerType>($3->getType()))
1892 GEN_ERROR("GetElementPtr requires a pointer operand");
1893
1894 const Type *IdxTy =
David Greene393be882007-09-04 15:46:09 +00001895 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 true);
1897 if (!IdxTy)
1898 GEN_ERROR("Index list invalid for constant getelementptr");
1899
1900 SmallVector<Constant*, 8> IdxVec;
1901 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1902 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1903 IdxVec.push_back(C);
1904 else
1905 GEN_ERROR("Indices to constant getelementptr must be constants");
1906
1907 delete $4;
1908
1909 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1910 CHECK_FOR_ERROR
1911 }
1912 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1913 if ($3->getType() != Type::Int1Ty)
1914 GEN_ERROR("Select condition must be of boolean type");
1915 if ($5->getType() != $7->getType())
1916 GEN_ERROR("Select operand types must match");
1917 $$ = ConstantExpr::getSelect($3, $5, $7);
1918 CHECK_FOR_ERROR
1919 }
1920 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1921 if ($3->getType() != $5->getType())
1922 GEN_ERROR("Binary operator types must match");
1923 CHECK_FOR_ERROR;
1924 $$ = ConstantExpr::get($1, $3, $5);
1925 }
1926 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1927 if ($3->getType() != $5->getType())
1928 GEN_ERROR("Logical operator types must match");
1929 if (!$3->getType()->isInteger()) {
1930 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1931 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1932 GEN_ERROR("Logical operator requires integral operands");
1933 }
1934 $$ = ConstantExpr::get($1, $3, $5);
1935 CHECK_FOR_ERROR
1936 }
1937 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1938 if ($4->getType() != $6->getType())
1939 GEN_ERROR("icmp operand types must match");
1940 $$ = ConstantExpr::getICmp($2, $4, $6);
1941 }
1942 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1943 if ($4->getType() != $6->getType())
1944 GEN_ERROR("fcmp operand types must match");
1945 $$ = ConstantExpr::getFCmp($2, $4, $6);
1946 }
1947 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1948 if (!ExtractElementInst::isValidOperands($3, $5))
1949 GEN_ERROR("Invalid extractelement operands");
1950 $$ = ConstantExpr::getExtractElement($3, $5);
1951 CHECK_FOR_ERROR
1952 }
1953 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1954 if (!InsertElementInst::isValidOperands($3, $5, $7))
1955 GEN_ERROR("Invalid insertelement operands");
1956 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1957 CHECK_FOR_ERROR
1958 }
1959 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1960 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1961 GEN_ERROR("Invalid shufflevector operands");
1962 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1963 CHECK_FOR_ERROR
1964 };
1965
1966
1967// ConstVector - A list of comma separated constants.
1968ConstVector : ConstVector ',' ConstVal {
1969 ($$ = $1)->push_back($3);
1970 CHECK_FOR_ERROR
1971 }
1972 | ConstVal {
1973 $$ = new std::vector<Constant*>();
1974 $$->push_back($1);
1975 CHECK_FOR_ERROR
1976 };
1977
1978
1979// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1980GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1981
1982// ThreadLocal
1983ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1984
1985// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1986AliaseeRef : ResultTypes SymbolicValueRef {
1987 const Type* VTy = $1->get();
1988 Value *V = getVal(VTy, $2);
Chris Lattner0f800522007-08-06 21:00:37 +00001989 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001990 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1991 if (!Aliasee)
1992 GEN_ERROR("Aliases can be created only to global values");
1993
1994 $$ = Aliasee;
1995 CHECK_FOR_ERROR
1996 delete $1;
1997 }
1998 | BITCAST '(' AliaseeRef TO Types ')' {
1999 Constant *Val = $3;
2000 const Type *DestTy = $5->get();
2001 if (!CastInst::castIsValid($1, $3, DestTy))
2002 GEN_ERROR("invalid cast opcode for cast from '" +
2003 Val->getType()->getDescription() + "' to '" +
2004 DestTy->getDescription() + "'");
2005
2006 $$ = ConstantExpr::getCast($1, $3, DestTy);
2007 CHECK_FOR_ERROR
2008 delete $5;
2009 };
2010
2011//===----------------------------------------------------------------------===//
2012// Rules to match Modules
2013//===----------------------------------------------------------------------===//
2014
2015// Module rule: Capture the result of parsing the whole file into a result
2016// variable...
2017//
2018Module
2019 : DefinitionList {
2020 $$ = ParserResult = CurModule.CurrentModule;
2021 CurModule.ModuleDone();
2022 CHECK_FOR_ERROR;
2023 }
2024 | /*empty*/ {
2025 $$ = ParserResult = CurModule.CurrentModule;
2026 CurModule.ModuleDone();
2027 CHECK_FOR_ERROR;
2028 }
2029 ;
2030
2031DefinitionList
2032 : Definition
2033 | DefinitionList Definition
2034 ;
2035
2036Definition
2037 : DEFINE { CurFun.isDeclare = false; } Function {
2038 CurFun.FunctionDone();
2039 CHECK_FOR_ERROR
2040 }
2041 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2042 CHECK_FOR_ERROR
2043 }
2044 | MODULE ASM_TOK AsmBlock {
2045 CHECK_FOR_ERROR
2046 }
2047 | OptLocalAssign TYPE Types {
2048 if (!UpRefs.empty())
2049 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2050 // Eagerly resolve types. This is not an optimization, this is a
2051 // requirement that is due to the fact that we could have this:
2052 //
2053 // %list = type { %list * }
2054 // %list = type { %list * } ; repeated type decl
2055 //
2056 // If types are not resolved eagerly, then the two types will not be
2057 // determined to be the same type!
2058 //
2059 ResolveTypeTo($1, *$3);
2060
2061 if (!setTypeName(*$3, $1) && !$1) {
2062 CHECK_FOR_ERROR
2063 // If this is a named type that is not a redefinition, add it to the slot
2064 // table.
2065 CurModule.Types.push_back(*$3);
2066 }
2067
2068 delete $3;
2069 CHECK_FOR_ERROR
2070 }
2071 | OptLocalAssign TYPE VOID {
2072 ResolveTypeTo($1, $3);
2073
2074 if (!setTypeName($3, $1) && !$1) {
2075 CHECK_FOR_ERROR
2076 // If this is a named type that is not a redefinition, add it to the slot
2077 // table.
2078 CurModule.Types.push_back($3);
2079 }
2080 CHECK_FOR_ERROR
2081 }
Christopher Lamb20a39e92007-12-12 08:44:39 +00002082 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2083 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084 /* "Externally Visible" Linkage */
2085 if ($5 == 0)
2086 GEN_ERROR("Global value initializer is not a constant");
2087 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb20a39e92007-12-12 08:44:39 +00002088 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb44d62f62007-12-11 08:59:05 +00002089 CHECK_FOR_ERROR
2090 } GlobalVarAttributes {
2091 CurGV = 0;
2092 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002093 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb20a39e92007-12-12 08:44:39 +00002094 ConstVal OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095 if ($6 == 0)
2096 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb20a39e92007-12-12 08:44:39 +00002097 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098 CHECK_FOR_ERROR
2099 } GlobalVarAttributes {
2100 CurGV = 0;
2101 }
2102 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb20a39e92007-12-12 08:44:39 +00002103 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 if (!UpRefs.empty())
2105 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb20a39e92007-12-12 08:44:39 +00002106 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107 CHECK_FOR_ERROR
2108 delete $6;
2109 } GlobalVarAttributes {
2110 CurGV = 0;
2111 CHECK_FOR_ERROR
2112 }
2113 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2114 std::string Name;
2115 if ($1) {
2116 Name = *$1;
2117 delete $1;
2118 }
2119 if (Name.empty())
2120 GEN_ERROR("Alias name cannot be empty");
2121
2122 Constant* Aliasee = $5;
2123 if (Aliasee == 0)
2124 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2125
2126 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2127 CurModule.CurrentModule);
2128 GA->setVisibility($2);
2129 InsertValue(GA, CurModule.Values);
Chris Lattner9d99b312007-09-10 23:23:53 +00002130
2131
2132 // If there was a forward reference of this alias, resolve it now.
2133
2134 ValID ID;
2135 if (!Name.empty())
2136 ID = ValID::createGlobalName(Name);
2137 else
2138 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2139
2140 if (GlobalValue *FWGV =
2141 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2142 // Replace uses of the fwdref with the actual alias.
2143 FWGV->replaceAllUsesWith(GA);
2144 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2145 GV->eraseFromParent();
2146 else
2147 cast<Function>(FWGV)->eraseFromParent();
2148 }
2149 ID.destroy();
2150
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002151 CHECK_FOR_ERROR
2152 }
2153 | TARGET TargetDefinition {
2154 CHECK_FOR_ERROR
2155 }
2156 | DEPLIBS '=' LibrariesDefinition {
2157 CHECK_FOR_ERROR
2158 }
2159 ;
2160
2161
2162AsmBlock : STRINGCONSTANT {
2163 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2164 if (AsmSoFar.empty())
2165 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2166 else
2167 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2168 delete $1;
2169 CHECK_FOR_ERROR
2170};
2171
2172TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2173 CurModule.CurrentModule->setTargetTriple(*$3);
2174 delete $3;
2175 }
2176 | DATALAYOUT '=' STRINGCONSTANT {
2177 CurModule.CurrentModule->setDataLayout(*$3);
2178 delete $3;
2179 };
2180
2181LibrariesDefinition : '[' LibList ']';
2182
2183LibList : LibList ',' STRINGCONSTANT {
2184 CurModule.CurrentModule->addLibrary(*$3);
2185 delete $3;
2186 CHECK_FOR_ERROR
2187 }
2188 | STRINGCONSTANT {
2189 CurModule.CurrentModule->addLibrary(*$1);
2190 delete $1;
2191 CHECK_FOR_ERROR
2192 }
2193 | /* empty: end of list */ {
2194 CHECK_FOR_ERROR
2195 }
2196 ;
2197
2198//===----------------------------------------------------------------------===//
2199// Rules to match Function Headers
2200//===----------------------------------------------------------------------===//
2201
2202ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2203 if (!UpRefs.empty())
2204 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2205 if (*$3 == Type::VoidTy)
2206 GEN_ERROR("void typed arguments are invalid");
2207 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2208 $$ = $1;
2209 $1->push_back(E);
2210 CHECK_FOR_ERROR
2211 }
2212 | Types OptParamAttrs OptLocalName {
2213 if (!UpRefs.empty())
2214 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2215 if (*$1 == Type::VoidTy)
2216 GEN_ERROR("void typed arguments are invalid");
2217 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2218 $$ = new ArgListType;
2219 $$->push_back(E);
2220 CHECK_FOR_ERROR
2221 };
2222
2223ArgList : ArgListH {
2224 $$ = $1;
2225 CHECK_FOR_ERROR
2226 }
2227 | ArgListH ',' DOTDOTDOT {
2228 $$ = $1;
2229 struct ArgListEntry E;
2230 E.Ty = new PATypeHolder(Type::VoidTy);
2231 E.Name = 0;
2232 E.Attrs = ParamAttr::None;
2233 $$->push_back(E);
2234 CHECK_FOR_ERROR
2235 }
2236 | DOTDOTDOT {
2237 $$ = new ArgListType;
2238 struct ArgListEntry E;
2239 E.Ty = new PATypeHolder(Type::VoidTy);
2240 E.Name = 0;
2241 E.Attrs = ParamAttr::None;
2242 $$->push_back(E);
2243 CHECK_FOR_ERROR
2244 }
2245 | /* empty */ {
2246 $$ = 0;
2247 CHECK_FOR_ERROR
2248 };
2249
2250FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002251 OptFuncAttrs OptSection OptAlign OptGC {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252 std::string FunctionName(*$3);
2253 delete $3; // Free strdup'd memory!
2254
2255 // Check the function result for abstractness if this is a define. We should
2256 // have no abstract types at this point
2257 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2258 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2259
2260 std::vector<const Type*> ParamTypeList;
2261 ParamAttrsVector Attrs;
2262 if ($7 != ParamAttr::None) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002263 ParamAttrsWithIndex PAWI;
2264 PAWI.index = 0;
2265 PAWI.attrs = $7;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002266 Attrs.push_back(PAWI);
2267 }
2268 if ($5) { // If there are arguments...
2269 unsigned index = 1;
2270 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2271 const Type* Ty = I->Ty->get();
2272 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2273 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2274 ParamTypeList.push_back(Ty);
2275 if (Ty != Type::VoidTy)
2276 if (I->Attrs != ParamAttr::None) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002277 ParamAttrsWithIndex PAWI;
2278 PAWI.index = index;
2279 PAWI.attrs = I->Attrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280 Attrs.push_back(PAWI);
2281 }
2282 }
2283 }
2284
2285 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2286 if (isVarArg) ParamTypeList.pop_back();
2287
Duncan Sandsc2141722007-11-30 18:19:18 +00002288 const ParamAttrsList *PAL = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002289 if (!Attrs.empty())
2290 PAL = ParamAttrsList::get(Attrs);
2291
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002292 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambbb2f2222007-12-17 01:12:55 +00002293 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294 delete $2;
2295
2296 ValID ID;
2297 if (!FunctionName.empty()) {
2298 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2299 } else {
2300 ID = ValID::createGlobalID(CurModule.Values.size());
2301 }
2302
2303 Function *Fn = 0;
2304 // See if this function was forward referenced. If so, recycle the object.
2305 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2306 // Move the function to the end of the list, from whereever it was
2307 // previously inserted.
2308 Fn = cast<Function>(FWRef);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002309 assert(!Fn->getParamAttrs() && "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310 CurModule.CurrentModule->getFunctionList().remove(Fn);
2311 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2312 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2313 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002314 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002315 // The existing function doesn't have the same type. This is an overload
2316 // error.
2317 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002318 } else if (Fn->getParamAttrs() != PAL) {
2319 // The existing function doesn't have the same parameter attributes.
2320 // This is an overload error.
2321 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002322 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2323 // Neither the existing or the current function is a declaration and they
2324 // have the same name and same type. Clearly this is a redefinition.
2325 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002326 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002327 // Make sure to strip off any argument names so we can't get conflicts.
2328 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2329 AI != AE; ++AI)
2330 AI->setName("");
2331 }
2332 } else { // Not already defined?
2333 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2334 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335 InsertValue(Fn, CurModule.Values);
2336 }
2337
2338 CurFun.FunctionStart(Fn);
2339
2340 if (CurFun.isDeclare) {
2341 // If we have declaration, always overwrite linkage. This will allow us to
2342 // correctly handle cases, when pointer to function is passed as argument to
2343 // another function.
2344 Fn->setLinkage(CurFun.Linkage);
2345 Fn->setVisibility(CurFun.Visibility);
2346 }
2347 Fn->setCallingConv($1);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002348 Fn->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002349 Fn->setAlignment($9);
2350 if ($8) {
2351 Fn->setSection(*$8);
2352 delete $8;
2353 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002354 if ($10) {
2355 Fn->setCollector($10->c_str());
2356 delete $10;
2357 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358
2359 // Add all of the arguments we parsed to the function...
2360 if ($5) { // Is null if empty...
2361 if (isVarArg) { // Nuke the last entry
2362 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2363 "Not a varargs marker!");
2364 delete $5->back().Ty;
2365 $5->pop_back(); // Delete the last entry
2366 }
2367 Function::arg_iterator ArgIt = Fn->arg_begin();
2368 Function::arg_iterator ArgEnd = Fn->arg_end();
2369 unsigned Idx = 1;
2370 for (ArgListType::iterator I = $5->begin();
2371 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2372 delete I->Ty; // Delete the typeholder...
2373 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2374 CHECK_FOR_ERROR
2375 InsertValue(ArgIt);
2376 Idx++;
2377 }
2378
2379 delete $5; // We're now done with the argument list
2380 }
2381 CHECK_FOR_ERROR
2382};
2383
2384BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2385
2386FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2387 $$ = CurFun.CurrentFunction;
2388
2389 // Make sure that we keep track of the linkage type even if there was a
2390 // previous "declare".
2391 $$->setLinkage($1);
2392 $$->setVisibility($2);
2393};
2394
2395END : ENDTOK | '}'; // Allow end of '}' to end a function
2396
2397Function : BasicBlockList END {
2398 $$ = $1;
2399 CHECK_FOR_ERROR
2400};
2401
2402FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2403 CurFun.CurrentFunction->setLinkage($1);
2404 CurFun.CurrentFunction->setVisibility($2);
2405 $$ = CurFun.CurrentFunction;
2406 CurFun.FunctionDone();
2407 CHECK_FOR_ERROR
2408 };
2409
2410//===----------------------------------------------------------------------===//
2411// Rules to match Basic Blocks
2412//===----------------------------------------------------------------------===//
2413
2414OptSideEffect : /* empty */ {
2415 $$ = false;
2416 CHECK_FOR_ERROR
2417 }
2418 | SIDEEFFECT {
2419 $$ = true;
2420 CHECK_FOR_ERROR
2421 };
2422
2423ConstValueRef : ESINT64VAL { // A reference to a direct constant
2424 $$ = ValID::create($1);
2425 CHECK_FOR_ERROR
2426 }
2427 | EUINT64VAL {
2428 $$ = ValID::create($1);
2429 CHECK_FOR_ERROR
2430 }
2431 | FPVAL { // Perhaps it's an FP constant?
2432 $$ = ValID::create($1);
2433 CHECK_FOR_ERROR
2434 }
2435 | TRUETOK {
2436 $$ = ValID::create(ConstantInt::getTrue());
2437 CHECK_FOR_ERROR
2438 }
2439 | FALSETOK {
2440 $$ = ValID::create(ConstantInt::getFalse());
2441 CHECK_FOR_ERROR
2442 }
2443 | NULL_TOK {
2444 $$ = ValID::createNull();
2445 CHECK_FOR_ERROR
2446 }
2447 | UNDEF {
2448 $$ = ValID::createUndef();
2449 CHECK_FOR_ERROR
2450 }
2451 | ZEROINITIALIZER { // A vector zero constant.
2452 $$ = ValID::createZeroInit();
2453 CHECK_FOR_ERROR
2454 }
2455 | '<' ConstVector '>' { // Nonempty unsized packed vector
2456 const Type *ETy = (*$2)[0]->getType();
2457 int NumElements = $2->size();
2458
2459 VectorType* pt = VectorType::get(ETy, NumElements);
2460 PATypeHolder* PTy = new PATypeHolder(
2461 HandleUpRefs(
2462 VectorType::get(
2463 ETy,
2464 NumElements)
2465 )
2466 );
2467
2468 // Verify all elements are correct type!
2469 for (unsigned i = 0; i < $2->size(); i++) {
2470 if (ETy != (*$2)[i]->getType())
2471 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2472 ETy->getDescription() +"' as required!\nIt is of type '" +
2473 (*$2)[i]->getType()->getDescription() + "'.");
2474 }
2475
2476 $$ = ValID::create(ConstantVector::get(pt, *$2));
2477 delete PTy; delete $2;
2478 CHECK_FOR_ERROR
2479 }
2480 | ConstExpr {
2481 $$ = ValID::create($1);
2482 CHECK_FOR_ERROR
2483 }
2484 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2485 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2486 delete $3;
2487 delete $5;
2488 CHECK_FOR_ERROR
2489 };
2490
2491// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2492// another value.
2493//
2494SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2495 $$ = ValID::createLocalID($1);
2496 CHECK_FOR_ERROR
2497 }
2498 | GLOBALVAL_ID {
2499 $$ = ValID::createGlobalID($1);
2500 CHECK_FOR_ERROR
2501 }
2502 | LocalName { // Is it a named reference...?
2503 $$ = ValID::createLocalName(*$1);
2504 delete $1;
2505 CHECK_FOR_ERROR
2506 }
2507 | GlobalName { // Is it a named reference...?
2508 $$ = ValID::createGlobalName(*$1);
2509 delete $1;
2510 CHECK_FOR_ERROR
2511 };
2512
2513// ValueRef - A reference to a definition... either constant or symbolic
2514ValueRef : SymbolicValueRef | ConstValueRef;
2515
2516
2517// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2518// type immediately preceeds the value reference, and allows complex constant
2519// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2520ResolvedVal : Types ValueRef {
2521 if (!UpRefs.empty())
2522 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2523 $$ = getVal(*$1, $2);
2524 delete $1;
2525 CHECK_FOR_ERROR
2526 }
2527 ;
2528
Devang Patel036f0382008-02-20 22:39:45 +00002529ReturnedVal : ResolvedVal {
2530 $$ = new std::vector<Value *>();
2531 $$->push_back($1);
2532 CHECK_FOR_ERROR
2533 }
Devang Patel1a932fc2008-02-23 00:35:18 +00002534 | ReturnedVal ',' ResolvedVal {
Devang Patel036f0382008-02-20 22:39:45 +00002535 ($$=$1)->push_back($3);
2536 CHECK_FOR_ERROR
2537 };
2538
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002539BasicBlockList : BasicBlockList BasicBlock {
2540 $$ = $1;
2541 CHECK_FOR_ERROR
2542 }
2543 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2544 $$ = $1;
2545 CHECK_FOR_ERROR
2546 };
2547
2548
2549// Basic blocks are terminated by branching instructions:
2550// br, br/cc, switch, ret
2551//
2552BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2553 setValueName($3, $2);
2554 CHECK_FOR_ERROR
2555 InsertValue($3);
2556 $1->getInstList().push_back($3);
2557 $$ = $1;
2558 CHECK_FOR_ERROR
2559 };
2560
2561InstructionList : InstructionList Inst {
2562 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2563 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2564 if (CI2->getParent() == 0)
2565 $1->getInstList().push_back(CI2);
2566 $1->getInstList().push_back($2);
2567 $$ = $1;
2568 CHECK_FOR_ERROR
2569 }
2570 | /* empty */ { // Empty space between instruction lists
2571 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2572 CHECK_FOR_ERROR
2573 }
2574 | LABELSTR { // Labelled (named) basic block
2575 $$ = defineBBVal(ValID::createLocalName(*$1));
2576 delete $1;
2577 CHECK_FOR_ERROR
2578
2579 };
2580
Devang Patel036f0382008-02-20 22:39:45 +00002581BBTerminatorInst :
2582 RET ReturnedVal { // Return with a result...
Devang Patelbbbb8202008-02-26 22:12:58 +00002583 ValueList &VL = *$2;
Devang Patel202ec472008-02-26 23:17:50 +00002584 assert(!VL.empty() && "Invalid ret operands!");
2585 $$ = new ReturnInst(&VL[0], VL.size());
Devang Patel036f0382008-02-20 22:39:45 +00002586 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587 CHECK_FOR_ERROR
2588 }
2589 | RET VOID { // Return with no result...
2590 $$ = new ReturnInst();
2591 CHECK_FOR_ERROR
2592 }
2593 | BR LABEL ValueRef { // Unconditional Branch...
2594 BasicBlock* tmpBB = getBBVal($3);
2595 CHECK_FOR_ERROR
2596 $$ = new BranchInst(tmpBB);
2597 } // Conditional Branch...
2598 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2599 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2600 BasicBlock* tmpBBA = getBBVal($6);
2601 CHECK_FOR_ERROR
2602 BasicBlock* tmpBBB = getBBVal($9);
2603 CHECK_FOR_ERROR
2604 Value* tmpVal = getVal(Type::Int1Ty, $3);
2605 CHECK_FOR_ERROR
2606 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2607 }
2608 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2609 Value* tmpVal = getVal($2, $3);
2610 CHECK_FOR_ERROR
2611 BasicBlock* tmpBB = getBBVal($6);
2612 CHECK_FOR_ERROR
2613 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2614 $$ = S;
2615
2616 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2617 E = $8->end();
2618 for (; I != E; ++I) {
2619 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2620 S->addCase(CI, I->second);
2621 else
2622 GEN_ERROR("Switch case is constant, but not a simple integer");
2623 }
2624 delete $8;
2625 CHECK_FOR_ERROR
2626 }
2627 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2628 Value* tmpVal = getVal($2, $3);
2629 CHECK_FOR_ERROR
2630 BasicBlock* tmpBB = getBBVal($6);
2631 CHECK_FOR_ERROR
2632 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2633 $$ = S;
2634 CHECK_FOR_ERROR
2635 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002636 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002637 TO LABEL ValueRef UNWIND LABEL ValueRef {
2638
2639 // Handle the short syntax
2640 const PointerType *PFTy = 0;
2641 const FunctionType *Ty = 0;
2642 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2643 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2644 // Pull out the types of all of the arguments...
2645 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002646 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002647 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002648 const Type *Ty = I->Val->getType();
2649 if (Ty == Type::VoidTy)
2650 GEN_ERROR("Short call syntax cannot be used with varargs");
2651 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002652 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002653 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambbb2f2222007-12-17 01:12:55 +00002654 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002655 }
2656
2657 delete $3;
2658
2659 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2660 CHECK_FOR_ERROR
2661 BasicBlock *Normal = getBBVal($11);
2662 CHECK_FOR_ERROR
2663 BasicBlock *Except = getBBVal($14);
2664 CHECK_FOR_ERROR
2665
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002666 ParamAttrsVector Attrs;
2667 if ($8 != ParamAttr::None) {
2668 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2669 Attrs.push_back(PAWI);
2670 }
2671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672 // Check the arguments
2673 ValueList Args;
2674 if ($6->empty()) { // Has no arguments?
2675 // Make sure no arguments is a good thing!
2676 if (Ty->getNumParams() != 0)
2677 GEN_ERROR("No arguments passed to a function that "
2678 "expects arguments");
2679 } else { // Has arguments?
2680 // Loop through FunctionType's arguments and ensure they are specified
2681 // correctly!
2682 FunctionType::param_iterator I = Ty->param_begin();
2683 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002684 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002685 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002687 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002688 if (ArgI->Val->getType() != *I)
2689 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2690 (*I)->getDescription() + "'");
2691 Args.push_back(ArgI->Val);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002692 if (ArgI->Attrs != ParamAttr::None) {
2693 ParamAttrsWithIndex PAWI;
2694 PAWI.index = index;
2695 PAWI.attrs = ArgI->Attrs;
2696 Attrs.push_back(PAWI);
2697 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002698 }
2699
2700 if (Ty->isVarArg()) {
2701 if (I == E)
Duncan Sands6c3314b2008-01-11 21:23:39 +00002702 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 Args.push_back(ArgI->Val); // push the remaining varargs
Duncan Sands6c3314b2008-01-11 21:23:39 +00002704 if (ArgI->Attrs != ParamAttr::None) {
2705 ParamAttrsWithIndex PAWI;
2706 PAWI.index = index;
2707 PAWI.attrs = ArgI->Attrs;
2708 Attrs.push_back(PAWI);
2709 }
2710 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002711 } else if (I != E || ArgI != ArgE)
2712 GEN_ERROR("Invalid number of parameters detected");
2713 }
2714
Duncan Sandsc2141722007-11-30 18:19:18 +00002715 const ParamAttrsList *PAL = 0;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002716 if (!Attrs.empty())
2717 PAL = ParamAttrsList::get(Attrs);
2718
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719 // Create the InvokeInst
David Greene8278ef52007-08-27 19:04:21 +00002720 InvokeInst *II = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002721 II->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002722 II->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 $$ = II;
2724 delete $6;
2725 CHECK_FOR_ERROR
2726 }
2727 | UNWIND {
2728 $$ = new UnwindInst();
2729 CHECK_FOR_ERROR
2730 }
2731 | UNREACHABLE {
2732 $$ = new UnreachableInst();
2733 CHECK_FOR_ERROR
2734 };
2735
2736
2737
2738JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2739 $$ = $1;
2740 Constant *V = cast<Constant>(getExistingVal($2, $3));
2741 CHECK_FOR_ERROR
2742 if (V == 0)
2743 GEN_ERROR("May only switch on a constant pool value");
2744
2745 BasicBlock* tmpBB = getBBVal($6);
2746 CHECK_FOR_ERROR
2747 $$->push_back(std::make_pair(V, tmpBB));
2748 }
2749 | IntType ConstValueRef ',' LABEL ValueRef {
2750 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2751 Constant *V = cast<Constant>(getExistingVal($1, $2));
2752 CHECK_FOR_ERROR
2753
2754 if (V == 0)
2755 GEN_ERROR("May only switch on a constant pool value");
2756
2757 BasicBlock* tmpBB = getBBVal($5);
2758 CHECK_FOR_ERROR
2759 $$->push_back(std::make_pair(V, tmpBB));
2760 };
2761
2762Inst : OptLocalAssign InstVal {
2763 // Is this definition named?? if so, assign the name...
2764 setValueName($2, $1);
2765 CHECK_FOR_ERROR
2766 InsertValue($2);
2767 $$ = $2;
2768 CHECK_FOR_ERROR
2769 };
2770
2771
2772PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2773 if (!UpRefs.empty())
2774 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2775 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2776 Value* tmpVal = getVal(*$1, $3);
2777 CHECK_FOR_ERROR
2778 BasicBlock* tmpBB = getBBVal($5);
2779 CHECK_FOR_ERROR
2780 $$->push_back(std::make_pair(tmpVal, tmpBB));
2781 delete $1;
2782 }
2783 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2784 $$ = $1;
2785 Value* tmpVal = getVal($1->front().first->getType(), $4);
2786 CHECK_FOR_ERROR
2787 BasicBlock* tmpBB = getBBVal($6);
2788 CHECK_FOR_ERROR
2789 $1->push_back(std::make_pair(tmpVal, tmpBB));
2790 };
2791
2792
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002793ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2794 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795 if (!UpRefs.empty())
2796 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2797 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00002798 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002799 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002800 $$->push_back(E);
2801 delete $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002802 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002803 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002804 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2805 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002806 // Labels are only valid in ASMs
2807 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002808 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002809 $$->push_back(E);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002810 CHECK_FOR_ERROR
Dale Johannesencfb19e62007-11-05 21:20:28 +00002811 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002812 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2813 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002814 if (!UpRefs.empty())
2815 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2816 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002817 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002818 $$->push_back(E);
2819 delete $3;
2820 CHECK_FOR_ERROR
2821 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002822 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2823 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002824 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002825 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002826 $$->push_back(E);
2827 CHECK_FOR_ERROR
2828 }
2829 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830
2831IndexList // Used for gep instructions and constant expressions
2832 : /*empty*/ { $$ = new std::vector<Value*>(); }
2833 | IndexList ',' ResolvedVal {
2834 $$ = $1;
2835 $$->push_back($3);
2836 CHECK_FOR_ERROR
2837 }
2838 ;
2839
2840OptTailCall : TAIL CALL {
2841 $$ = true;
2842 CHECK_FOR_ERROR
2843 }
2844 | CALL {
2845 $$ = false;
2846 CHECK_FOR_ERROR
2847 };
2848
2849InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2850 if (!UpRefs.empty())
2851 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2852 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2853 !isa<VectorType>((*$2).get()))
2854 GEN_ERROR(
2855 "Arithmetic operator requires integer, FP, or packed operands");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002856 Value* val1 = getVal(*$2, $3);
2857 CHECK_FOR_ERROR
2858 Value* val2 = getVal(*$2, $5);
2859 CHECK_FOR_ERROR
2860 $$ = BinaryOperator::create($1, val1, val2);
2861 if ($$ == 0)
2862 GEN_ERROR("binary operator returned null");
2863 delete $2;
2864 }
2865 | LogicalOps Types ValueRef ',' ValueRef {
2866 if (!UpRefs.empty())
2867 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2868 if (!(*$2)->isInteger()) {
2869 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2870 !cast<VectorType>($2->get())->getElementType()->isInteger())
2871 GEN_ERROR("Logical operator requires integral operands");
2872 }
2873 Value* tmpVal1 = getVal(*$2, $3);
2874 CHECK_FOR_ERROR
2875 Value* tmpVal2 = getVal(*$2, $5);
2876 CHECK_FOR_ERROR
2877 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2878 if ($$ == 0)
2879 GEN_ERROR("binary operator returned null");
2880 delete $2;
2881 }
2882 | ICMP IPredicates Types ValueRef ',' ValueRef {
2883 if (!UpRefs.empty())
2884 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2885 if (isa<VectorType>((*$3).get()))
2886 GEN_ERROR("Vector types not supported by icmp instruction");
2887 Value* tmpVal1 = getVal(*$3, $4);
2888 CHECK_FOR_ERROR
2889 Value* tmpVal2 = getVal(*$3, $6);
2890 CHECK_FOR_ERROR
2891 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2892 if ($$ == 0)
2893 GEN_ERROR("icmp operator returned null");
2894 delete $3;
2895 }
2896 | FCMP FPredicates Types ValueRef ',' ValueRef {
2897 if (!UpRefs.empty())
2898 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2899 if (isa<VectorType>((*$3).get()))
2900 GEN_ERROR("Vector types not supported by fcmp instruction");
2901 Value* tmpVal1 = getVal(*$3, $4);
2902 CHECK_FOR_ERROR
2903 Value* tmpVal2 = getVal(*$3, $6);
2904 CHECK_FOR_ERROR
2905 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2906 if ($$ == 0)
2907 GEN_ERROR("fcmp operator returned null");
2908 delete $3;
2909 }
2910 | CastOps ResolvedVal TO Types {
2911 if (!UpRefs.empty())
2912 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2913 Value* Val = $2;
2914 const Type* DestTy = $4->get();
2915 if (!CastInst::castIsValid($1, Val, DestTy))
2916 GEN_ERROR("invalid cast opcode for cast from '" +
2917 Val->getType()->getDescription() + "' to '" +
2918 DestTy->getDescription() + "'");
2919 $$ = CastInst::create($1, Val, DestTy);
2920 delete $4;
2921 }
2922 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2923 if ($2->getType() != Type::Int1Ty)
2924 GEN_ERROR("select condition must be boolean");
2925 if ($4->getType() != $6->getType())
2926 GEN_ERROR("select value types should match");
2927 $$ = new SelectInst($2, $4, $6);
2928 CHECK_FOR_ERROR
2929 }
2930 | VAARG ResolvedVal ',' Types {
2931 if (!UpRefs.empty())
2932 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2933 $$ = new VAArgInst($2, *$4);
2934 delete $4;
2935 CHECK_FOR_ERROR
2936 }
2937 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2938 if (!ExtractElementInst::isValidOperands($2, $4))
2939 GEN_ERROR("Invalid extractelement operands");
2940 $$ = new ExtractElementInst($2, $4);
2941 CHECK_FOR_ERROR
2942 }
2943 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2944 if (!InsertElementInst::isValidOperands($2, $4, $6))
2945 GEN_ERROR("Invalid insertelement operands");
2946 $$ = new InsertElementInst($2, $4, $6);
2947 CHECK_FOR_ERROR
2948 }
2949 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2950 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2951 GEN_ERROR("Invalid shufflevector operands");
2952 $$ = new ShuffleVectorInst($2, $4, $6);
2953 CHECK_FOR_ERROR
2954 }
2955 | PHI_TOK PHIList {
2956 const Type *Ty = $2->front().first->getType();
2957 if (!Ty->isFirstClassType())
2958 GEN_ERROR("PHI node operands must be of first class type");
2959 $$ = new PHINode(Ty);
2960 ((PHINode*)$$)->reserveOperandSpace($2->size());
2961 while ($2->begin() != $2->end()) {
2962 if ($2->front().first->getType() != Ty)
2963 GEN_ERROR("All elements of a PHI node must be of the same type");
2964 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2965 $2->pop_front();
2966 }
2967 delete $2; // Free the list...
2968 CHECK_FOR_ERROR
2969 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002970 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971 OptFuncAttrs {
2972
2973 // Handle the short syntax
2974 const PointerType *PFTy = 0;
2975 const FunctionType *Ty = 0;
2976 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2977 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2978 // Pull out the types of all of the arguments...
2979 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002980 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002981 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002982 const Type *Ty = I->Val->getType();
2983 if (Ty == Type::VoidTy)
2984 GEN_ERROR("Short call syntax cannot be used with varargs");
2985 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002987 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambbb2f2222007-12-17 01:12:55 +00002988 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989 }
2990
2991 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2992 CHECK_FOR_ERROR
2993
2994 // Check for call to invalid intrinsic to avoid crashing later.
2995 if (Function *theF = dyn_cast<Function>(V)) {
2996 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2997 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2998 !theF->getIntrinsicID(true))
2999 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3000 theF->getName() + "'");
3001 }
3002
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003003 // Set up the ParamAttrs for the function
3004 ParamAttrsVector Attrs;
3005 if ($8 != ParamAttr::None) {
3006 ParamAttrsWithIndex PAWI;
3007 PAWI.index = 0;
3008 PAWI.attrs = $8;
3009 Attrs.push_back(PAWI);
3010 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011 // Check the arguments
3012 ValueList Args;
3013 if ($6->empty()) { // Has no arguments?
3014 // Make sure no arguments is a good thing!
3015 if (Ty->getNumParams() != 0)
3016 GEN_ERROR("No arguments passed to a function that "
3017 "expects arguments");
3018 } else { // Has arguments?
3019 // Loop through FunctionType's arguments and ensure they are specified
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003020 // correctly. Also, gather any parameter attributes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 FunctionType::param_iterator I = Ty->param_begin();
3022 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00003023 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003024 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003025
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003026 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 if (ArgI->Val->getType() != *I)
3028 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3029 (*I)->getDescription() + "'");
3030 Args.push_back(ArgI->Val);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003031 if (ArgI->Attrs != ParamAttr::None) {
3032 ParamAttrsWithIndex PAWI;
3033 PAWI.index = index;
3034 PAWI.attrs = ArgI->Attrs;
3035 Attrs.push_back(PAWI);
3036 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 }
3038 if (Ty->isVarArg()) {
3039 if (I == E)
Duncan Sands6c3314b2008-01-11 21:23:39 +00003040 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041 Args.push_back(ArgI->Val); // push the remaining varargs
Duncan Sands6c3314b2008-01-11 21:23:39 +00003042 if (ArgI->Attrs != ParamAttr::None) {
3043 ParamAttrsWithIndex PAWI;
3044 PAWI.index = index;
3045 PAWI.attrs = ArgI->Attrs;
3046 Attrs.push_back(PAWI);
3047 }
3048 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003049 } else if (I != E || ArgI != ArgE)
3050 GEN_ERROR("Invalid number of parameters detected");
3051 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003052
3053 // Finish off the ParamAttrs and check them
Duncan Sandsc2141722007-11-30 18:19:18 +00003054 const ParamAttrsList *PAL = 0;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003055 if (!Attrs.empty())
3056 PAL = ParamAttrsList::get(Attrs);
3057
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058 // Create the call node
David Greeneb1c4a7b2007-08-01 03:43:44 +00003059 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003060 CI->setTailCall($1);
3061 CI->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003062 CI->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003063 $$ = CI;
3064 delete $6;
3065 delete $3;
3066 CHECK_FOR_ERROR
3067 }
3068 | MemoryInst {
3069 $$ = $1;
3070 CHECK_FOR_ERROR
3071 };
3072
3073OptVolatile : VOLATILE {
3074 $$ = true;
3075 CHECK_FOR_ERROR
3076 }
3077 | /* empty */ {
3078 $$ = false;
3079 CHECK_FOR_ERROR
3080 };
3081
3082
3083
3084MemoryInst : MALLOC Types OptCAlign {
3085 if (!UpRefs.empty())
3086 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3087 $$ = new MallocInst(*$2, 0, $3);
3088 delete $2;
3089 CHECK_FOR_ERROR
3090 }
3091 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3092 if (!UpRefs.empty())
3093 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3094 Value* tmpVal = getVal($4, $5);
3095 CHECK_FOR_ERROR
3096 $$ = new MallocInst(*$2, tmpVal, $6);
3097 delete $2;
3098 }
3099 | ALLOCA Types OptCAlign {
3100 if (!UpRefs.empty())
3101 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3102 $$ = new AllocaInst(*$2, 0, $3);
3103 delete $2;
3104 CHECK_FOR_ERROR
3105 }
3106 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3107 if (!UpRefs.empty())
3108 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3109 Value* tmpVal = getVal($4, $5);
3110 CHECK_FOR_ERROR
3111 $$ = new AllocaInst(*$2, tmpVal, $6);
3112 delete $2;
3113 }
3114 | FREE ResolvedVal {
3115 if (!isa<PointerType>($2->getType()))
3116 GEN_ERROR("Trying to free nonpointer type " +
3117 $2->getType()->getDescription() + "");
3118 $$ = new FreeInst($2);
3119 CHECK_FOR_ERROR
3120 }
3121
3122 | OptVolatile LOAD Types ValueRef OptCAlign {
3123 if (!UpRefs.empty())
3124 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3125 if (!isa<PointerType>($3->get()))
3126 GEN_ERROR("Can't load from nonpointer type: " +
3127 (*$3)->getDescription());
3128 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3129 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3130 (*$3)->getDescription());
3131 Value* tmpVal = getVal(*$3, $4);
3132 CHECK_FOR_ERROR
3133 $$ = new LoadInst(tmpVal, "", $1, $5);
3134 delete $3;
3135 }
3136 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3137 if (!UpRefs.empty())
3138 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3139 const PointerType *PT = dyn_cast<PointerType>($5->get());
3140 if (!PT)
3141 GEN_ERROR("Can't store to a nonpointer type: " +
3142 (*$5)->getDescription());
3143 const Type *ElTy = PT->getElementType();
3144 if (ElTy != $3->getType())
3145 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3146 "' into space of type '" + ElTy->getDescription() + "'");
3147
3148 Value* tmpVal = getVal(*$5, $6);
3149 CHECK_FOR_ERROR
3150 $$ = new StoreInst($3, tmpVal, $1, $7);
3151 delete $5;
3152 }
Devang Patel89c3d672008-02-22 19:31:15 +00003153| GETRESULT Types SymbolicValueRef ',' EUINT64VAL {
3154 Value *TmpVal = getVal($2->get(), $3);
Devang Patele5c806a2008-02-19 22:26:37 +00003155 if (!GetResultInst::isValidOperands(TmpVal, $5))
3156 GEN_ERROR("Invalid getresult operands");
3157 $$ = new GetResultInst(TmpVal, $5);
Devang Patel1a932fc2008-02-23 00:35:18 +00003158 delete $2;
Devang Patele5c806a2008-02-19 22:26:37 +00003159 CHECK_FOR_ERROR
3160 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161 | GETELEMENTPTR Types ValueRef IndexList {
3162 if (!UpRefs.empty())
3163 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3164 if (!isa<PointerType>($2->get()))
3165 GEN_ERROR("getelementptr insn requires pointer operand");
3166
David Greene393be882007-09-04 15:46:09 +00003167 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 GEN_ERROR("Invalid getelementptr indices for type '" +
3169 (*$2)->getDescription()+ "'");
3170 Value* tmpVal = getVal(*$2, $3);
3171 CHECK_FOR_ERROR
David Greene393be882007-09-04 15:46:09 +00003172 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173 delete $2;
3174 delete $4;
3175 };
3176
3177
3178%%
3179
3180// common code from the two 'RunVMAsmParser' functions
3181static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003183 // Check to make sure the parser succeeded
3184 if (yyparse()) {
3185 if (ParserResult)
3186 delete ParserResult;
3187 return 0;
3188 }
3189
3190 // Emit an error if there are any unresolved types left.
3191 if (!CurModule.LateResolveTypes.empty()) {
3192 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3193 if (DID.Type == ValID::LocalName) {
3194 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3195 } else {
3196 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3197 }
3198 if (ParserResult)
3199 delete ParserResult;
3200 return 0;
3201 }
3202
3203 // Emit an error if there are any unresolved values left.
3204 if (!CurModule.LateResolveValues.empty()) {
3205 Value *V = CurModule.LateResolveValues.back();
3206 std::map<Value*, std::pair<ValID, int> >::iterator I =
3207 CurModule.PlaceHolderInfo.find(V);
3208
3209 if (I != CurModule.PlaceHolderInfo.end()) {
3210 ValID &DID = I->second.first;
3211 if (DID.Type == ValID::LocalName) {
3212 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3213 } else {
3214 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3215 }
3216 if (ParserResult)
3217 delete ParserResult;
3218 return 0;
3219 }
3220 }
3221
3222 // Check to make sure that parsing produced a result
3223 if (!ParserResult)
3224 return 0;
3225
3226 // Reset ParserResult variable while saving its value for the result.
3227 Module *Result = ParserResult;
3228 ParserResult = 0;
3229
3230 return Result;
3231}
3232
3233void llvm::GenerateError(const std::string &message, int LineNo) {
Chris Lattner17e73c22007-11-18 08:46:26 +00003234 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003235 // TODO: column number in exception
3236 if (TheParseError)
Chris Lattner17e73c22007-11-18 08:46:26 +00003237 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003238 TriggerError = 1;
3239}
3240
3241int yyerror(const char *ErrorMsg) {
Chris Lattner17e73c22007-11-18 08:46:26 +00003242 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003243 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Chris Lattner17e73c22007-11-18 08:46:26 +00003244 if (yychar != YYEMPTY && yychar != 0) {
3245 errMsg += " while reading token: '";
3246 errMsg += std::string(LLLgetTokenStart(),
3247 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3248 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 GenerateError(errMsg);
3250 return 0;
3251}