1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "UpgradeInternals.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"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
30 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
31 // relating to upreferences in the input stream.
33 //#define DEBUG_UPREFS 1
35 #define UR_OUT(X) std::cerr << X
40 #define YYERROR_VERBOSE 1
41 #define YYINCLUDED_STDLIB_H
47 int yyerror(const char*);
48 static void warning(const std::string& WarningMsg);
52 std::istream* LexInput;
53 static std::string CurFilename;
55 // This bool controls whether attributes are ever added to function declarations
56 // definitions and calls.
57 static bool AddAttributes = false;
59 static Module *ParserResult;
60 static bool ObsoleteVarArgs;
61 static bool NewVarArgs;
62 static BasicBlock *CurBB;
63 static GlobalVariable *CurGV;
65 // This contains info used when building the body of a function. It is
66 // destroyed when the function is completed.
68 typedef std::vector<Value *> ValueList; // Numbered defs
70 typedef std::pair<std::string,TypeInfo> RenameMapKey;
71 typedef std::map<RenameMapKey,std::string> RenameMapType;
74 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
75 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
77 static struct PerModuleInfo {
78 Module *CurrentModule;
79 std::map<const Type *, ValueList> Values; // Module level numbered definitions
80 std::map<const Type *,ValueList> LateResolveValues;
81 std::vector<PATypeHolder> Types;
82 std::vector<Signedness> TypeSigns;
83 std::map<std::string,Signedness> NamedTypeSigns;
84 std::map<std::string,Signedness> NamedValueSigns;
85 std::map<ValID, PATypeHolder> LateResolveTypes;
86 static Module::Endianness Endian;
87 static Module::PointerSize PointerSize;
88 RenameMapType RenameMap;
90 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
91 /// how they were referenced and on which line of the input they came from so
92 /// that we can resolve them later and print error messages as appropriate.
93 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
95 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
96 // references to global values. Global values may be referenced before they
97 // are defined, and if so, the temporary object that they represent is held
98 // here. This is used for forward references of GlobalValues.
100 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
102 GlobalRefsType GlobalRefs;
105 // If we could not resolve some functions at function compilation time
106 // (calls to functions before they are defined), resolve them now... Types
107 // are resolved when the constant pool has been completely parsed.
109 ResolveDefinitions(LateResolveValues);
111 // Check to make sure that all global value forward references have been
114 if (!GlobalRefs.empty()) {
115 std::string UndefinedReferences = "Unresolved global references exist:\n";
117 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
119 UndefinedReferences += " " + I->first.first->getDescription() + " " +
120 I->first.second.getName() + "\n";
122 error(UndefinedReferences);
126 if (CurrentModule->getDataLayout().empty()) {
127 std::string dataLayout;
128 if (Endian != Module::AnyEndianness)
129 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
130 if (PointerSize != Module::AnyPointerSize) {
131 if (!dataLayout.empty())
133 dataLayout.append(PointerSize == Module::Pointer64 ?
134 "p:64:64" : "p:32:32");
136 CurrentModule->setDataLayout(dataLayout);
139 Values.clear(); // Clear out function local definitions
142 NamedTypeSigns.clear();
143 NamedValueSigns.clear();
147 // GetForwardRefForGlobal - Check to see if there is a forward reference
148 // for this global. If so, remove it from the GlobalRefs map and return it.
149 // If not, just return null.
150 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
151 // Check to see if there is a forward reference to this global variable...
152 // if there is, eliminate it and patch the reference to use the new def'n.
153 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
154 GlobalValue *Ret = 0;
155 if (I != GlobalRefs.end()) {
161 void setEndianness(Module::Endianness E) { Endian = E; }
162 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
165 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
166 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
168 static struct PerFunctionInfo {
169 Function *CurrentFunction; // Pointer to current function being created
171 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
172 std::map<const Type*, ValueList> LateResolveValues;
173 bool isDeclare; // Is this function a forward declararation?
174 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
176 /// BBForwardRefs - When we see forward references to basic blocks, keep
177 /// track of them here.
178 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
179 std::vector<BasicBlock*> NumberedBlocks;
180 RenameMapType RenameMap;
183 inline PerFunctionInfo() {
186 Linkage = GlobalValue::ExternalLinkage;
189 inline void FunctionStart(Function *M) {
194 void FunctionDone() {
195 NumberedBlocks.clear();
197 // Any forward referenced blocks left?
198 if (!BBForwardRefs.empty()) {
199 error("Undefined reference to label " +
200 BBForwardRefs.begin()->first->getName());
204 // Resolve all forward references now.
205 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
207 Values.clear(); // Clear out function local definitions
211 Linkage = GlobalValue::ExternalLinkage;
213 } CurFun; // Info for the current function...
215 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
217 /// This function is just a utility to make a Key value for the rename map.
218 /// The Key is a combination of the name, type, Signedness of the original
219 /// value (global/function). This just constructs the key and ensures that
220 /// named Signedness values are resolved to the actual Signedness.
221 /// @brief Make a key for the RenameMaps
222 static RenameMapKey makeRenameMapKey(const std::string &Name, const Type* Ty,
223 const Signedness &Sign) {
227 // Don't allow Named Signedness nodes because they won't match. The actual
228 // Signedness must be looked up in the NamedTypeSigns map.
229 TI.S.copy(CurModule.NamedTypeSigns[Sign.getName()]);
232 return std::make_pair(Name, TI);
236 //===----------------------------------------------------------------------===//
237 // Code to handle definitions of all the types
238 //===----------------------------------------------------------------------===//
240 static int InsertValue(Value *V,
241 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
242 if (V->hasName()) return -1; // Is this a numbered definition?
244 // Yes, insert the value into the value table...
245 ValueList &List = ValueTab[V->getType()];
247 return List.size()-1;
250 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
252 case ValID::NumberVal: // Is it a numbered definition?
253 // Module constants occupy the lowest numbered slots...
254 if ((unsigned)D.Num < CurModule.Types.size()) {
255 return CurModule.Types[(unsigned)D.Num];
258 case ValID::NameVal: // Is it a named definition?
259 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
264 error("Internal parser error: Invalid symbol type reference");
268 // If we reached here, we referenced either a symbol that we don't know about
269 // or an id number that hasn't been read yet. We may be referencing something
270 // forward, so just create an entry to be resolved later and get to it...
272 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
274 if (inFunctionScope()) {
275 if (D.Type == ValID::NameVal) {
276 error("Reference to an undefined type: '" + D.getName() + "'");
279 error("Reference to an undefined type: #" + itostr(D.Num));
284 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
285 if (I != CurModule.LateResolveTypes.end())
288 Type *Typ = OpaqueType::get();
289 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
293 /// This is like the getType method except that instead of looking up the type
294 /// for a given ID, it looks up that type's sign.
295 /// @brief Get the signedness of a referenced type
296 static Signedness getTypeSign(const ValID &D) {
298 case ValID::NumberVal: // Is it a numbered definition?
299 // Module constants occupy the lowest numbered slots...
300 if ((unsigned)D.Num < CurModule.TypeSigns.size()) {
301 return CurModule.TypeSigns[(unsigned)D.Num];
304 case ValID::NameVal: { // Is it a named definition?
305 std::map<std::string,Signedness>::const_iterator I =
306 CurModule.NamedTypeSigns.find(D.Name);
307 if (I != CurModule.NamedTypeSigns.end())
309 // Perhaps its a named forward .. just cache the name
317 // If we don't find it, its signless
323 /// This function is analagous to getElementType in LLVM. It provides the same
324 /// function except that it looks up the Signedness instead of the type. This is
325 /// used when processing GEP instructions that need to extract the type of an
326 /// indexed struct/array/ptr member.
327 /// @brief Look up an element's sign.
328 static Signedness getElementSign(const ValueInfo& VI,
329 const std::vector<Value*> &Indices) {
330 const Type *Ptr = VI.V->getType();
331 assert(isa<PointerType>(Ptr) && "Need pointer type");
335 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
336 if (CurIdx == Indices.size())
339 Value *Index = Indices[CurIdx++];
340 assert(!isa<PointerType>(CT) || CurIdx == 1 && "Invalid type");
341 Ptr = CT->getTypeAtIndex(Index);
342 if (const Type* Ty = Ptr->getForwardedType())
344 assert(S.isComposite() && "Bad Signedness type");
345 if (isa<StructType>(CT)) {
346 S = S.get(cast<ConstantInt>(Index)->getZExtValue());
351 S = CurModule.NamedTypeSigns[S.getName()];
354 Result.makeComposite(S);
358 /// This function just translates a ConstantInfo into a ValueInfo and calls
359 /// getElementSign(ValueInfo,...). Its just a convenience.
360 /// @brief ConstantInfo version of getElementSign.
361 static Signedness getElementSign(const ConstInfo& CI,
362 const std::vector<Constant*> &Indices) {
366 std::vector<Value*> Idx;
367 for (unsigned i = 0; i < Indices.size(); ++i)
368 Idx.push_back(Indices[i]);
369 Signedness result = getElementSign(VI, Idx);
374 /// This function determines if two function types differ only in their use of
375 /// the sret parameter attribute in the first argument. If they are identical
376 /// in all other respects, it returns true. Otherwise, it returns false.
377 static bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
378 const FunctionType *F2) {
379 if (F1->getReturnType() != F2->getReturnType() ||
380 F1->getNumParams() != F2->getNumParams() ||
381 F1->getParamAttrs(0) != F2->getParamAttrs(0))
383 unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
384 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
385 if (F1->getParamType(i) != F2->getParamType(i) ||
386 unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
387 unsigned(F2->getParamAttrs(i+1)) & SRetMask)
393 /// This function determines if the type of V and Ty differ only by the SRet
394 /// parameter attribute. This is a more generalized case of
395 /// FuncTysDIfferOnlyBySRet since it doesn't require FunctionType arguments.
396 static bool TypesDifferOnlyBySRet(Value *V, const Type* Ty) {
397 if (V->getType() == Ty)
399 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
400 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
402 const FunctionType* FT1 = dyn_cast<FunctionType>(PF1->getElementType());
403 const FunctionType* FT2 = dyn_cast<FunctionType>(PF2->getElementType());
405 return FuncTysDifferOnlyBySRet(FT1, FT2);
410 // The upgrade of csretcc to sret param attribute may have caused a function
411 // to not be found because the param attribute changed the type of the called
412 // function. This helper function, used in getExistingValue, detects that
413 // situation and bitcasts the function to the correct type.
414 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
415 // Handle degenerate cases
418 if (V->getType() == Ty)
421 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
422 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
424 const FunctionType *FT1 = dyn_cast<FunctionType>(PF1->getElementType());
425 const FunctionType *FT2 = dyn_cast<FunctionType>(PF2->getElementType());
426 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
427 if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
429 else if (Constant *C = dyn_cast<Constant>(V))
430 return ConstantExpr::getBitCast(C, PF1);
432 return new BitCastInst(V, PF1, "upgrd.cast", CurBB);
438 // getExistingValue - Look up the value specified by the provided type and
439 // the provided ValID. If the value exists and has already been defined, return
440 // it. Otherwise return null.
442 static Value *getExistingValue(const Type *Ty, const ValID &D) {
443 if (isa<FunctionType>(Ty)) {
444 error("Functions are not values and must be referenced as pointers");
448 case ValID::NumberVal: { // Is it a numbered definition?
449 unsigned Num = (unsigned)D.Num;
451 // Module constants occupy the lowest numbered slots...
452 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
453 if (VI != CurModule.Values.end()) {
454 if (Num < VI->second.size())
455 return VI->second[Num];
456 Num -= VI->second.size();
459 // Make sure that our type is within bounds
460 VI = CurFun.Values.find(Ty);
461 if (VI == CurFun.Values.end()) return 0;
463 // Check that the number is within bounds...
464 if (VI->second.size() <= Num) return 0;
466 return VI->second[Num];
469 case ValID::NameVal: { // Is it a named definition?
470 // Get the name out of the ID
471 RenameMapKey Key = makeRenameMapKey(D.Name, Ty, D.S);
473 if (inFunctionScope()) {
474 // See if the name was renamed
475 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
476 std::string LookupName;
477 if (I != CurFun.RenameMap.end())
478 LookupName = I->second;
481 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
482 V = SymTab.lookup(LookupName);
483 if (V && V->getType() != Ty)
484 V = handleSRetFuncTypeMerge(V, Ty);
485 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type");
488 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
489 std::string LookupName;
490 if (I != CurModule.RenameMap.end())
491 LookupName = I->second;
494 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
495 if (V && V->getType() != Ty)
496 V = handleSRetFuncTypeMerge(V, Ty);
497 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type");
502 D.destroy(); // Free old strdup'd memory...
506 // Check to make sure that "Ty" is an integral type, and that our
507 // value will fit into the specified type...
508 case ValID::ConstSIntVal: // Is it a constant pool reference??
509 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
510 error("Signed integral constant '" + itostr(D.ConstPool64) +
511 "' is invalid for type '" + Ty->getDescription() + "'");
513 return ConstantInt::get(Ty, D.ConstPool64);
515 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
516 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
517 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
518 error("Integral constant '" + utostr(D.UConstPool64) +
519 "' is invalid or out of range");
520 else // This is really a signed reference. Transmogrify.
521 return ConstantInt::get(Ty, D.ConstPool64);
523 return ConstantInt::get(Ty, D.UConstPool64);
525 case ValID::ConstFPVal: // Is it a floating point const pool reference?
526 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
527 error("FP constant invalid for type");
528 return ConstantFP::get(Ty, D.ConstPoolFP);
530 case ValID::ConstNullVal: // Is it a null value?
531 if (!isa<PointerType>(Ty))
532 error("Cannot create a a non pointer null");
533 return ConstantPointerNull::get(cast<PointerType>(Ty));
535 case ValID::ConstUndefVal: // Is it an undef value?
536 return UndefValue::get(Ty);
538 case ValID::ConstZeroVal: // Is it a zero value?
539 return Constant::getNullValue(Ty);
541 case ValID::ConstantVal: // Fully resolved constant?
542 if (D.ConstantValue->getType() != Ty)
543 error("Constant expression type different from required type");
544 return D.ConstantValue;
546 case ValID::InlineAsmVal: { // Inline asm expression
547 const PointerType *PTy = dyn_cast<PointerType>(Ty);
548 const FunctionType *FTy =
549 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
550 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
551 error("Invalid type for asm constraint string");
552 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
553 D.IAD->HasSideEffects);
554 D.destroy(); // Free InlineAsmDescriptor.
558 assert(0 && "Unhandled case");
562 assert(0 && "Unhandled case");
566 // getVal - This function is identical to getExistingValue, except that if a
567 // value is not already defined, it "improvises" by creating a placeholder var
568 // that looks and acts just like the requested variable. When the value is
569 // defined later, all uses of the placeholder variable are replaced with the
572 static Value *getVal(const Type *Ty, const ValID &ID) {
573 if (Ty == Type::LabelTy)
574 error("Cannot use a basic block here");
576 // See if the value has already been defined.
577 Value *V = getExistingValue(Ty, ID);
580 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
581 error("Invalid use of a composite type");
583 // If we reached here, we referenced either a symbol that we don't know about
584 // or an id number that hasn't been read yet. We may be referencing something
585 // forward, so just create an entry to be resolved later and get to it...
586 V = new Argument(Ty);
588 // Remember where this forward reference came from. FIXME, shouldn't we try
589 // to recycle these things??
590 CurModule.PlaceHolderInfo.insert(
591 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
593 if (inFunctionScope())
594 InsertValue(V, CurFun.LateResolveValues);
596 InsertValue(V, CurModule.LateResolveValues);
600 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
601 static std::string makeNameUnique(const std::string& Name) {
602 static unsigned UniqueNameCounter = 1;
603 std::string Result(Name);
604 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
608 /// getBBVal - This is used for two purposes:
609 /// * If isDefinition is true, a new basic block with the specified ID is being
611 /// * If isDefinition is true, this is a reference to a basic block, which may
612 /// or may not be a forward reference.
614 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
615 assert(inFunctionScope() && "Can't get basic block at global scope");
621 error("Illegal label reference " + ID.getName());
623 case ValID::NumberVal: // Is it a numbered definition?
624 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
625 CurFun.NumberedBlocks.resize(ID.Num+1);
626 BB = CurFun.NumberedBlocks[ID.Num];
628 case ValID::NameVal: // Is it a named definition?
630 if (Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name)) {
631 if (N->getType() != Type::LabelTy) {
632 // Register names didn't use to conflict with basic block names
633 // because of type planes. Now they all have to be unique. So, we just
634 // rename the register and treat this name as if no basic block
636 RenameMapKey Key = makeRenameMapKey(ID.Name, N->getType(), ID.S);
637 N->setName(makeNameUnique(N->getName()));
638 CurModule.RenameMap[Key] = N->getName();
641 BB = cast<BasicBlock>(N);
647 // See if the block has already been defined.
649 // If this is the definition of the block, make sure the existing value was
650 // just a forward reference. If it was a forward reference, there will be
651 // an entry for it in the PlaceHolderInfo map.
652 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
653 // The existing value was a definition, not a forward reference.
654 error("Redefinition of label " + ID.getName());
656 ID.destroy(); // Free strdup'd memory.
660 // Otherwise this block has not been seen before.
661 BB = new BasicBlock("", CurFun.CurrentFunction);
662 if (ID.Type == ValID::NameVal) {
663 BB->setName(ID.Name);
665 CurFun.NumberedBlocks[ID.Num] = BB;
668 // If this is not a definition, keep track of it so we can use it as a forward
671 // Remember where this forward reference came from.
672 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
674 // The forward declaration could have been inserted anywhere in the
675 // function: insert it into the correct place now.
676 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
677 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
684 //===----------------------------------------------------------------------===//
685 // Code to handle forward references in instructions
686 //===----------------------------------------------------------------------===//
688 // This code handles the late binding needed with statements that reference
689 // values not defined yet... for example, a forward branch, or the PHI node for
692 // This keeps a table (CurFun.LateResolveValues) of all such forward references
693 // and back patchs after we are done.
696 // ResolveDefinitions - If we could not resolve some defs at parsing
697 // time (forward branches, phi functions for loops, etc...) resolve the
701 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
702 std::map<const Type*,ValueList> *FutureLateResolvers) {
704 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
705 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
706 E = LateResolvers.end(); LRI != E; ++LRI) {
707 const Type* Ty = LRI->first;
708 ValueList &List = LRI->second;
709 while (!List.empty()) {
710 Value *V = List.back();
713 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
714 CurModule.PlaceHolderInfo.find(V);
715 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
717 ValID &DID = PHI->second.first;
719 Value *TheRealValue = getExistingValue(Ty, DID);
721 V->replaceAllUsesWith(TheRealValue);
723 CurModule.PlaceHolderInfo.erase(PHI);
724 } else if (FutureLateResolvers) {
725 // Functions have their unresolved items forwarded to the module late
727 InsertValue(V, *FutureLateResolvers);
729 if (DID.Type == ValID::NameVal) {
730 error("Reference to an invalid definition: '" + DID.getName() +
731 "' of type '" + V->getType()->getDescription() + "'",
735 error("Reference to an invalid definition: #" +
736 itostr(DID.Num) + " of type '" +
737 V->getType()->getDescription() + "'", PHI->second.second);
744 LateResolvers.clear();
747 /// This function is used for type resolution and upref handling. When a type
748 /// becomes concrete, this function is called to adjust the signedness for the
750 static void ResolveTypeSign(const Type* oldTy, const Signedness &Sign) {
751 std::string TyName = CurModule.CurrentModule->getTypeName(oldTy);
753 CurModule.NamedTypeSigns[TyName] = Sign;
756 /// ResolveTypeTo - A brand new type was just declared. This means that (if
757 /// name is not null) things referencing Name can be resolved. Otherwise,
758 /// things refering to the number can be resolved. Do this now.
759 static void ResolveTypeTo(char *Name, const Type *ToTy, const Signedness& Sign){
762 D = ValID::create(Name);
764 D = ValID::create((int)CurModule.Types.size());
767 CurModule.NamedTypeSigns[Name] = Sign;
769 std::map<ValID, PATypeHolder>::iterator I =
770 CurModule.LateResolveTypes.find(D);
771 if (I != CurModule.LateResolveTypes.end()) {
772 const Type *OldTy = I->second.get();
773 ((DerivedType*)OldTy)->refineAbstractTypeTo(ToTy);
774 CurModule.LateResolveTypes.erase(I);
778 /// This is the implementation portion of TypeHasInteger. It traverses the
779 /// type given, avoiding recursive types, and returns true as soon as it finds
780 /// an integer type. If no integer type is found, it returns false.
781 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
782 // Handle some easy cases
783 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
787 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
788 return STy->getElementType()->isInteger();
790 // Avoid type structure recursion
791 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
796 // Push us on the type stack
799 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
800 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
802 FunctionType::param_iterator I = FTy->param_begin();
803 FunctionType::param_iterator E = FTy->param_end();
805 if (TypeHasIntegerI(*I, Stack))
808 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
809 StructType::element_iterator I = STy->element_begin();
810 StructType::element_iterator E = STy->element_end();
811 for (; I != E; ++I) {
812 if (TypeHasIntegerI(*I, Stack))
817 // There shouldn't be anything else, but its definitely not integer
818 assert(0 && "What type is this?");
822 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
823 /// to avoid recursion, and then calls TypeHasIntegerI.
824 static inline bool TypeHasInteger(const Type *Ty) {
825 std::vector<const Type*> TyStack;
826 return TypeHasIntegerI(Ty, TyStack);
829 // setValueName - Set the specified value to the name given. The name may be
830 // null potentially, in which case this is a noop. The string passed in is
831 // assumed to be a malloc'd string buffer, and is free'd by this function.
833 static void setValueName(const ValueInfo &V, char *NameStr) {
835 std::string Name(NameStr); // Copy string
836 free(NameStr); // Free old string
838 if (V.V->getType() == Type::VoidTy) {
839 error("Can't assign name '" + Name + "' to value with void type");
843 assert(inFunctionScope() && "Must be in function scope");
845 // Search the function's symbol table for an existing value of this name
846 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
847 Value* Existing = ST.lookup(Name);
849 // An existing value of the same name was found. This might have happened
850 // because of the integer type planes collapsing in LLVM 2.0.
851 if (Existing->getType() == V.V->getType() &&
852 !TypeHasInteger(Existing->getType())) {
853 // If the type does not contain any integers in them then this can't be
854 // a type plane collapsing issue. It truly is a redefinition and we
855 // should error out as the assembly is invalid.
856 error("Redefinition of value named '" + Name + "' of type '" +
857 V.V->getType()->getDescription() + "'");
860 // In LLVM 2.0 we don't allow names to be re-used for any values in a
861 // function, regardless of Type. Previously re-use of names was okay as
862 // long as they were distinct types. With type planes collapsing because
863 // of the signedness change and because of PR411, this can no longer be
864 // supported. We must search the entire symbol table for a conflicting
865 // name and make the name unique. No warning is needed as this can't
867 std::string NewName = makeNameUnique(Name);
868 // We're changing the name but it will probably be used by other
869 // instructions as operands later on. Consequently we have to retain
870 // a mapping of the renaming that we're doing.
871 RenameMapKey Key = makeRenameMapKey(Name, V.V->getType(), V.S);
872 CurFun.RenameMap[Key] = NewName;
881 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
882 /// this is a declaration, otherwise it is a definition.
883 static GlobalVariable *
884 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
885 bool isConstantGlobal, const Type *Ty,
886 Constant *Initializer,
887 const Signedness &Sign) {
888 if (isa<FunctionType>(Ty))
889 error("Cannot declare global vars of function type");
891 const PointerType *PTy = PointerType::get(Ty);
895 Name = NameStr; // Copy string
896 free(NameStr); // Free old string
899 // See if this global value was forward referenced. If so, recycle the
903 ID = ValID::create((char*)Name.c_str());
905 ID = ValID::create((int)CurModule.Values[PTy].size());
907 ID.S.makeComposite(Sign);
909 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
910 // Move the global to the end of the list, from whereever it was
911 // previously inserted.
912 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
913 CurModule.CurrentModule->getGlobalList().remove(GV);
914 CurModule.CurrentModule->getGlobalList().push_back(GV);
915 GV->setInitializer(Initializer);
916 GV->setLinkage(Linkage);
917 GV->setConstant(isConstantGlobal);
918 InsertValue(GV, CurModule.Values);
922 // If this global has a name, check to see if there is already a definition
923 // of this global in the module and emit warnings if there are conflicts.
925 // The global has a name. See if there's an existing one of the same name.
926 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
927 // We found an existing global ov the same name. This isn't allowed
928 // in LLVM 2.0. Consequently, we must alter the name of the global so it
929 // can at least compile. This can happen because of type planes
930 // There is alread a global of the same name which means there is a
931 // conflict. Let's see what we can do about it.
932 std::string NewName(makeNameUnique(Name));
933 if (Linkage != GlobalValue::InternalLinkage) {
934 // The linkage of this gval is external so we can't reliably rename
935 // it because it could potentially create a linking problem.
936 // However, we can't leave the name conflict in the output either or
937 // it won't assemble with LLVM 2.0. So, all we can do is rename
938 // this one to something unique and emit a warning about the problem.
939 warning("Renaming global variable '" + Name + "' to '" + NewName +
940 "' may cause linkage errors");
943 // Put the renaming in the global rename map
944 RenameMapKey Key = makeRenameMapKey(Name, PointerType::get(Ty), ID.S);
945 CurModule.RenameMap[Key] = NewName;
952 // Otherwise there is no existing GV to use, create one now.
954 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
955 CurModule.CurrentModule);
956 InsertValue(GV, CurModule.Values);
957 // Remember the sign of this global.
958 CurModule.NamedValueSigns[Name] = ID.S;
962 // setTypeName - Set the specified type to the name given. The name may be
963 // null potentially, in which case this is a noop. The string passed in is
964 // assumed to be a malloc'd string buffer, and is freed by this function.
966 // This function returns true if the type has already been defined, but is
967 // allowed to be redefined in the specified context. If the name is a new name
968 // for the type plane, it is inserted and false is returned.
969 static bool setTypeName(const PATypeInfo& TI, char *NameStr) {
970 assert(!inFunctionScope() && "Can't give types function-local names");
971 if (NameStr == 0) return false;
973 std::string Name(NameStr); // Copy string
974 free(NameStr); // Free old string
976 const Type* Ty = TI.PAT->get();
978 // We don't allow assigning names to void type
979 if (Ty == Type::VoidTy) {
980 error("Can't assign name '" + Name + "' to the void type");
984 // Set the type name, checking for conflicts as we do so.
985 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, Ty);
987 // Save the sign information for later use
988 CurModule.NamedTypeSigns[Name] = TI.S;
990 if (AlreadyExists) { // Inserting a name that is already defined???
991 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
992 assert(Existing && "Conflict but no matching type?");
994 // There is only one case where this is allowed: when we are refining an
995 // opaque type. In this case, Existing will be an opaque type.
996 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
997 // We ARE replacing an opaque type!
998 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(Ty);
1002 // Otherwise, this is an attempt to redefine a type. That's okay if
1003 // the redefinition is identical to the original. This will be so if
1004 // Existing and T point to the same Type object. In this one case we
1005 // allow the equivalent redefinition.
1006 if (Existing == Ty) return true; // Yes, it's equal.
1008 // Any other kind of (non-equivalent) redefinition is an error.
1009 error("Redefinition of type named '" + Name + "' in the '" +
1010 Ty->getDescription() + "' type plane");
1016 //===----------------------------------------------------------------------===//
1017 // Code for handling upreferences in type names...
1020 // TypeContains - Returns true if Ty directly contains E in it.
1022 static bool TypeContains(const Type *Ty, const Type *E) {
1023 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
1024 E) != Ty->subtype_end();
1028 struct UpRefRecord {
1029 // NestingLevel - The number of nesting levels that need to be popped before
1030 // this type is resolved.
1031 unsigned NestingLevel;
1033 // LastContainedTy - This is the type at the current binding level for the
1034 // type. Every time we reduce the nesting level, this gets updated.
1035 const Type *LastContainedTy;
1037 // UpRefTy - This is the actual opaque type that the upreference is
1038 // represented with.
1039 OpaqueType *UpRefTy;
1041 UpRefRecord(unsigned NL, OpaqueType *URTy)
1042 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) { }
1046 // UpRefs - A list of the outstanding upreferences that need to be resolved.
1047 static std::vector<UpRefRecord> UpRefs;
1049 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1050 /// called. It loops through the UpRefs vector, which is a list of the
1051 /// currently active types. For each type, if the up reference is contained in
1052 /// the newly completed type, we decrement the level count. When the level
1053 /// count reaches zero, the upreferenced type is the type that is passed in:
1054 /// thus we can complete the cycle.
1056 static PATypeHolder HandleUpRefs(const Type *ty, const Signedness& Sign) {
1057 // If Ty isn't abstract, or if there are no up-references in it, then there is
1058 // nothing to resolve here.
1059 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1061 PATypeHolder Ty(ty);
1062 UR_OUT("Type '" << Ty->getDescription() <<
1063 "' newly formed. Resolving upreferences.\n" <<
1064 UpRefs.size() << " upreferences active!\n");
1066 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1067 // to zero), we resolve them all together before we resolve them to Ty. At
1068 // the end of the loop, if there is anything to resolve to Ty, it will be in
1070 OpaqueType *TypeToResolve = 0;
1073 for (; i != UpRefs.size(); ++i) {
1074 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1075 << UpRefs[i].UpRefTy->getDescription() << ") = "
1076 << (TypeContains(Ty, UpRefs[i].UpRefTy) ? "true" : "false") << "\n");
1077 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
1078 // Decrement level of upreference
1079 unsigned Level = --UpRefs[i].NestingLevel;
1080 UpRefs[i].LastContainedTy = Ty;
1081 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
1082 if (Level == 0) { // Upreference should be resolved!
1083 if (!TypeToResolve) {
1084 TypeToResolve = UpRefs[i].UpRefTy;
1086 UR_OUT(" * Resolving upreference for "
1087 << UpRefs[i].UpRefTy->getDescription() << "\n";
1088 std::string OldName = UpRefs[i].UpRefTy->getDescription());
1089 ResolveTypeSign(UpRefs[i].UpRefTy, Sign);
1090 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1091 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
1092 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
1094 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
1095 --i; // Do not skip the next element...
1100 if (TypeToResolve) {
1101 UR_OUT(" * Resolving upreference for "
1102 << UpRefs[i].UpRefTy->getDescription() << "\n";
1103 std::string OldName = TypeToResolve->getDescription());
1104 ResolveTypeSign(TypeToResolve, Sign);
1105 TypeToResolve->refineAbstractTypeTo(Ty);
1111 bool Signedness::operator<(const Signedness &that) const {
1114 return *(this->name) < *(that.name);
1116 return CurModule.NamedTypeSigns[*name] < that;
1117 } else if (that.isNamed()) {
1118 return *this < CurModule.NamedTypeSigns[*that.name];
1121 if (isComposite() && that.isComposite()) {
1122 if (sv->size() == that.sv->size()) {
1123 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1124 SignVector::const_iterator thatI = that.sv->begin(),
1125 thatE = that.sv->end();
1126 for (; thisI != thisE; ++thisI, ++thatI) {
1127 if (*thisI < *thatI)
1129 else if (!(*thisI == *thatI))
1134 return sv->size() < that.sv->size();
1136 return kind < that.kind;
1139 bool Signedness::operator==(const Signedness &that) const {
1142 return *(this->name) == *(that.name);
1144 return CurModule.NamedTypeSigns[*(this->name)] == that;
1145 else if (that.isNamed())
1146 return *this == CurModule.NamedTypeSigns[*(that.name)];
1147 if (isComposite() && that.isComposite()) {
1148 if (sv->size() == that.sv->size()) {
1149 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1150 SignVector::const_iterator thatI = that.sv->begin(),
1151 thatE = that.sv->end();
1152 for (; thisI != thisE; ++thisI, ++thatI) {
1153 if (!(*thisI == *thatI))
1160 return kind == that.kind;
1163 void Signedness::copy(const Signedness &that) {
1164 if (that.isNamed()) {
1166 name = new std::string(*that.name);
1167 } else if (that.isComposite()) {
1169 sv = new SignVector();
1177 void Signedness::destroy() {
1180 } else if (isComposite()) {
1186 void Signedness::dump() const {
1187 if (isComposite()) {
1188 if (sv->size() == 1) {
1193 for (unsigned i = 0; i < sv->size(); ++i) {
1200 } else if (isNamed()) {
1202 } else if (isSigned()) {
1204 } else if (isUnsigned()) {
1211 static inline Instruction::TermOps
1212 getTermOp(TermOps op) {
1214 default : assert(0 && "Invalid OldTermOp");
1215 case RetOp : return Instruction::Ret;
1216 case BrOp : return Instruction::Br;
1217 case SwitchOp : return Instruction::Switch;
1218 case InvokeOp : return Instruction::Invoke;
1219 case UnwindOp : return Instruction::Unwind;
1220 case UnreachableOp: return Instruction::Unreachable;
1224 static inline Instruction::BinaryOps
1225 getBinaryOp(BinaryOps op, const Type *Ty, const Signedness& Sign) {
1227 default : assert(0 && "Invalid OldBinaryOps");
1233 case SetGT : assert(0 && "Should use getCompareOp");
1234 case AddOp : return Instruction::Add;
1235 case SubOp : return Instruction::Sub;
1236 case MulOp : return Instruction::Mul;
1238 // This is an obsolete instruction so we must upgrade it based on the
1239 // types of its operands.
1240 bool isFP = Ty->isFloatingPoint();
1241 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1242 // If its a vector type we want to use the element type
1243 isFP = PTy->getElementType()->isFloatingPoint();
1245 return Instruction::FDiv;
1246 else if (Sign.isSigned())
1247 return Instruction::SDiv;
1248 return Instruction::UDiv;
1250 case UDivOp : return Instruction::UDiv;
1251 case SDivOp : return Instruction::SDiv;
1252 case FDivOp : return Instruction::FDiv;
1254 // This is an obsolete instruction so we must upgrade it based on the
1255 // types of its operands.
1256 bool isFP = Ty->isFloatingPoint();
1257 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1258 // If its a vector type we want to use the element type
1259 isFP = PTy->getElementType()->isFloatingPoint();
1260 // Select correct opcode
1262 return Instruction::FRem;
1263 else if (Sign.isSigned())
1264 return Instruction::SRem;
1265 return Instruction::URem;
1267 case URemOp : return Instruction::URem;
1268 case SRemOp : return Instruction::SRem;
1269 case FRemOp : return Instruction::FRem;
1270 case LShrOp : return Instruction::LShr;
1271 case AShrOp : return Instruction::AShr;
1272 case ShlOp : return Instruction::Shl;
1274 if (Sign.isSigned())
1275 return Instruction::AShr;
1276 return Instruction::LShr;
1277 case AndOp : return Instruction::And;
1278 case OrOp : return Instruction::Or;
1279 case XorOp : return Instruction::Xor;
1283 static inline Instruction::OtherOps
1284 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1285 const Signedness &Sign) {
1286 bool isSigned = Sign.isSigned();
1287 bool isFP = Ty->isFloatingPoint();
1289 default : assert(0 && "Invalid OldSetCC");
1292 predicate = FCmpInst::FCMP_OEQ;
1293 return Instruction::FCmp;
1295 predicate = ICmpInst::ICMP_EQ;
1296 return Instruction::ICmp;
1300 predicate = FCmpInst::FCMP_UNE;
1301 return Instruction::FCmp;
1303 predicate = ICmpInst::ICMP_NE;
1304 return Instruction::ICmp;
1308 predicate = FCmpInst::FCMP_OLE;
1309 return Instruction::FCmp;
1312 predicate = ICmpInst::ICMP_SLE;
1314 predicate = ICmpInst::ICMP_ULE;
1315 return Instruction::ICmp;
1319 predicate = FCmpInst::FCMP_OGE;
1320 return Instruction::FCmp;
1323 predicate = ICmpInst::ICMP_SGE;
1325 predicate = ICmpInst::ICMP_UGE;
1326 return Instruction::ICmp;
1330 predicate = FCmpInst::FCMP_OLT;
1331 return Instruction::FCmp;
1334 predicate = ICmpInst::ICMP_SLT;
1336 predicate = ICmpInst::ICMP_ULT;
1337 return Instruction::ICmp;
1341 predicate = FCmpInst::FCMP_OGT;
1342 return Instruction::FCmp;
1345 predicate = ICmpInst::ICMP_SGT;
1347 predicate = ICmpInst::ICMP_UGT;
1348 return Instruction::ICmp;
1353 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1355 default : assert(0 && "Invalid OldMemoryOps");
1356 case MallocOp : return Instruction::Malloc;
1357 case FreeOp : return Instruction::Free;
1358 case AllocaOp : return Instruction::Alloca;
1359 case LoadOp : return Instruction::Load;
1360 case StoreOp : return Instruction::Store;
1361 case GetElementPtrOp : return Instruction::GetElementPtr;
1365 static inline Instruction::OtherOps
1366 getOtherOp(OtherOps op, const Signedness &Sign) {
1368 default : assert(0 && "Invalid OldOtherOps");
1369 case PHIOp : return Instruction::PHI;
1370 case CallOp : return Instruction::Call;
1371 case SelectOp : return Instruction::Select;
1372 case UserOp1 : return Instruction::UserOp1;
1373 case UserOp2 : return Instruction::UserOp2;
1374 case VAArg : return Instruction::VAArg;
1375 case ExtractElementOp : return Instruction::ExtractElement;
1376 case InsertElementOp : return Instruction::InsertElement;
1377 case ShuffleVectorOp : return Instruction::ShuffleVector;
1378 case ICmpOp : return Instruction::ICmp;
1379 case FCmpOp : return Instruction::FCmp;
1383 static inline Value*
1384 getCast(CastOps op, Value *Src, const Signedness &SrcSign, const Type *DstTy,
1385 const Signedness &DstSign, bool ForceInstruction = false) {
1386 Instruction::CastOps Opcode;
1387 const Type* SrcTy = Src->getType();
1389 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1390 // fp -> ptr cast is no longer supported but we must upgrade this
1391 // by doing a double cast: fp -> int -> ptr
1392 SrcTy = Type::Int64Ty;
1393 Opcode = Instruction::IntToPtr;
1394 if (isa<Constant>(Src)) {
1395 Src = ConstantExpr::getCast(Instruction::FPToUI,
1396 cast<Constant>(Src), SrcTy);
1398 std::string NewName(makeNameUnique(Src->getName()));
1399 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1401 } else if (isa<IntegerType>(DstTy) &&
1402 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1403 // cast type %x to bool was previously defined as setne type %x, null
1404 // The cast semantic is now to truncate, not compare so we must retain
1405 // the original intent by replacing the cast with a setne
1406 Constant* Null = Constant::getNullValue(SrcTy);
1407 Instruction::OtherOps Opcode = Instruction::ICmp;
1408 unsigned short predicate = ICmpInst::ICMP_NE;
1409 if (SrcTy->isFloatingPoint()) {
1410 Opcode = Instruction::FCmp;
1411 predicate = FCmpInst::FCMP_ONE;
1412 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1413 error("Invalid cast to bool");
1415 if (isa<Constant>(Src) && !ForceInstruction)
1416 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1418 return CmpInst::create(Opcode, predicate, Src, Null);
1420 // Determine the opcode to use by calling CastInst::getCastOpcode
1422 CastInst::getCastOpcode(Src, SrcSign.isSigned(), DstTy,
1423 DstSign.isSigned());
1425 } else switch (op) {
1426 default: assert(0 && "Invalid cast token");
1427 case TruncOp: Opcode = Instruction::Trunc; break;
1428 case ZExtOp: Opcode = Instruction::ZExt; break;
1429 case SExtOp: Opcode = Instruction::SExt; break;
1430 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1431 case FPExtOp: Opcode = Instruction::FPExt; break;
1432 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1433 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1434 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1435 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1436 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1437 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1438 case BitCastOp: Opcode = Instruction::BitCast; break;
1441 if (isa<Constant>(Src) && !ForceInstruction)
1442 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1443 return CastInst::create(Opcode, Src, DstTy);
1446 static Instruction *
1447 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1448 std::vector<Value*>& Args) {
1450 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1451 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1452 if (Args.size() != 2)
1453 error("Invalid prototype for " + Name + " prototype");
1454 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1456 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1457 std::vector<const Type*> Params;
1458 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1459 if (Args.size() != 1)
1460 error("Invalid prototype for " + Name + " prototype");
1461 Params.push_back(PtrTy);
1462 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1463 const PointerType *PFTy = PointerType::get(FTy);
1464 Value* Func = getVal(PFTy, ID);
1465 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1466 return new CallInst(Func, &Args[0], Args.size());
1467 } else if (Name == "llvm.va_copy") {
1468 if (Args.size() != 2)
1469 error("Invalid prototype for " + Name + " prototype");
1470 Params.push_back(PtrTy);
1471 Params.push_back(PtrTy);
1472 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1473 const PointerType *PFTy = PointerType::get(FTy);
1474 Value* Func = getVal(PFTy, ID);
1475 std::string InstName0(makeNameUnique("va0"));
1476 std::string InstName1(makeNameUnique("va1"));
1477 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1478 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1479 return new CallInst(Func, &Args[0], Args.size());
1485 const Type* upgradeGEPIndices(const Type* PTy,
1486 std::vector<ValueInfo> *Indices,
1487 std::vector<Value*> &VIndices,
1488 std::vector<Constant*> *CIndices = 0) {
1489 // Traverse the indices with a gep_type_iterator so we can build the list
1490 // of constant and value indices for use later. Also perform upgrades
1492 if (CIndices) CIndices->clear();
1493 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1494 VIndices.push_back((*Indices)[i].V);
1495 generic_gep_type_iterator<std::vector<Value*>::iterator>
1496 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1497 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1498 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1499 Value *Index = VIndices[i];
1500 if (CIndices && !isa<Constant>(Index))
1501 error("Indices to constant getelementptr must be constants");
1502 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1503 // struct indices to i32 struct indices with ZExt for compatibility.
1504 else if (isa<StructType>(*GTI)) { // Only change struct indices
1505 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1506 if (CUI->getType()->getBitWidth() == 8)
1508 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1510 // Make sure that unsigned SequentialType indices are zext'd to
1511 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1512 // all indices for SequentialType elements. We must retain the same
1513 // semantic (zext) for unsigned types.
1514 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1515 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1517 Index = ConstantExpr::getCast(Instruction::ZExt,
1518 cast<Constant>(Index), Type::Int64Ty);
1520 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1521 makeNameUnique("gep"), CurBB);
1522 VIndices[i] = Index;
1525 // Add to the CIndices list, if requested.
1527 CIndices->push_back(cast<Constant>(Index));
1531 GetElementPtrInst::getIndexedType(PTy, &VIndices[0], VIndices.size(), true);
1533 error("Index list invalid for constant getelementptr");
1537 unsigned upgradeCallingConv(unsigned CC) {
1539 case OldCallingConv::C : return CallingConv::C;
1540 case OldCallingConv::CSRet : return CallingConv::C;
1541 case OldCallingConv::Fast : return CallingConv::Fast;
1542 case OldCallingConv::Cold : return CallingConv::Cold;
1543 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1544 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1550 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1551 bool debug, bool addAttrs)
1554 CurFilename = infile;
1557 AddAttributes = addAttrs;
1558 ObsoleteVarArgs = false;
1561 CurModule.CurrentModule = new Module(CurFilename);
1563 // Check to make sure the parser succeeded
1566 delete ParserResult;
1567 std::cerr << "llvm-upgrade: parse failed.\n";
1571 // Check to make sure that parsing produced a result
1572 if (!ParserResult) {
1573 std::cerr << "llvm-upgrade: no parse result.\n";
1577 // Reset ParserResult variable while saving its value for the result.
1578 Module *Result = ParserResult;
1581 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1584 if ((F = Result->getFunction("llvm.va_start"))
1585 && F->getFunctionType()->getNumParams() == 0)
1586 ObsoleteVarArgs = true;
1587 if((F = Result->getFunction("llvm.va_copy"))
1588 && F->getFunctionType()->getNumParams() == 1)
1589 ObsoleteVarArgs = true;
1592 if (ObsoleteVarArgs && NewVarArgs) {
1593 error("This file is corrupt: it uses both new and old style varargs");
1597 if(ObsoleteVarArgs) {
1598 if(Function* F = Result->getFunction("llvm.va_start")) {
1599 if (F->arg_size() != 0) {
1600 error("Obsolete va_start takes 0 argument");
1606 //bar = alloca typeof(foo)
1610 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1611 const Type* ArgTy = F->getFunctionType()->getReturnType();
1612 const Type* ArgTyPtr = PointerType::get(ArgTy);
1613 Function* NF = cast<Function>(Result->getOrInsertFunction(
1614 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1616 while (!F->use_empty()) {
1617 CallInst* CI = cast<CallInst>(F->use_back());
1618 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1619 new CallInst(NF, bar, "", CI);
1620 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1621 CI->replaceAllUsesWith(foo);
1622 CI->getParent()->getInstList().erase(CI);
1624 Result->getFunctionList().erase(F);
1627 if(Function* F = Result->getFunction("llvm.va_end")) {
1628 if(F->arg_size() != 1) {
1629 error("Obsolete va_end takes 1 argument");
1635 //bar = alloca 1 of typeof(foo)
1637 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1638 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1639 const Type* ArgTyPtr = PointerType::get(ArgTy);
1640 Function* NF = cast<Function>(Result->getOrInsertFunction(
1641 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1643 while (!F->use_empty()) {
1644 CallInst* CI = cast<CallInst>(F->use_back());
1645 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1646 new StoreInst(CI->getOperand(1), bar, CI);
1647 new CallInst(NF, bar, "", CI);
1648 CI->getParent()->getInstList().erase(CI);
1650 Result->getFunctionList().erase(F);
1653 if(Function* F = Result->getFunction("llvm.va_copy")) {
1654 if(F->arg_size() != 1) {
1655 error("Obsolete va_copy takes 1 argument");
1660 //a = alloca 1 of typeof(foo)
1661 //b = alloca 1 of typeof(foo)
1666 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1667 const Type* ArgTy = F->getFunctionType()->getReturnType();
1668 const Type* ArgTyPtr = PointerType::get(ArgTy);
1669 Function* NF = cast<Function>(Result->getOrInsertFunction(
1670 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1672 while (!F->use_empty()) {
1673 CallInst* CI = cast<CallInst>(F->use_back());
1674 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1675 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1676 new StoreInst(CI->getOperand(1), b, CI);
1677 new CallInst(NF, a, b, "", CI);
1678 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1679 CI->replaceAllUsesWith(foo);
1680 CI->getParent()->getInstList().erase(CI);
1682 Result->getFunctionList().erase(F);
1689 } // end llvm namespace
1691 using namespace llvm;
1696 llvm::Module *ModuleVal;
1697 llvm::Function *FunctionVal;
1698 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1699 llvm::BasicBlock *BasicBlockVal;
1700 llvm::TermInstInfo TermInstVal;
1701 llvm::InstrInfo InstVal;
1702 llvm::ConstInfo ConstVal;
1703 llvm::ValueInfo ValueVal;
1704 llvm::PATypeInfo TypeVal;
1705 llvm::TypeInfo PrimType;
1706 llvm::PHIListInfo PHIList;
1707 std::list<llvm::PATypeInfo> *TypeList;
1708 std::vector<llvm::ValueInfo> *ValueList;
1709 std::vector<llvm::ConstInfo> *ConstVector;
1712 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1713 // Represent the RHS of PHI node
1714 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1716 llvm::GlobalValue::LinkageTypes Linkage;
1724 char *StrVal; // This memory is strdup'd!
1725 llvm::ValID ValIDVal; // strdup'd memory maybe!
1727 llvm::BinaryOps BinaryOpVal;
1728 llvm::TermOps TermOpVal;
1729 llvm::MemoryOps MemOpVal;
1730 llvm::OtherOps OtherOpVal;
1731 llvm::CastOps CastOpVal;
1732 llvm::ICmpInst::Predicate IPred;
1733 llvm::FCmpInst::Predicate FPred;
1734 llvm::Module::Endianness Endianness;
1737 %type <ModuleVal> Module FunctionList
1738 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1739 %type <BasicBlockVal> BasicBlock InstructionList
1740 %type <TermInstVal> BBTerminatorInst
1741 %type <InstVal> Inst InstVal MemoryInst
1742 %type <ConstVal> ConstVal ConstExpr
1743 %type <ConstVector> ConstVector
1744 %type <ArgList> ArgList ArgListH
1745 %type <ArgVal> ArgVal
1746 %type <PHIList> PHIList
1747 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1748 %type <ValueList> IndexList // For GEP derived indices
1749 %type <TypeList> TypeListI ArgTypeListI
1750 %type <JumpTable> JumpTable
1751 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1752 %type <BoolVal> OptVolatile // 'volatile' or not
1753 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1754 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1755 %type <Linkage> OptLinkage FnDeclareLinkage
1756 %type <Endianness> BigOrLittle
1758 // ValueRef - Unresolved reference to a definition or BB
1759 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1760 %type <ValueVal> ResolvedVal // <type> <valref> pair
1762 // Tokens and types for handling constant integer values
1764 // ESINT64VAL - A negative number within long long range
1765 %token <SInt64Val> ESINT64VAL
1767 // EUINT64VAL - A positive number within uns. long long range
1768 %token <UInt64Val> EUINT64VAL
1769 %type <SInt64Val> EINT64VAL
1771 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1772 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1773 %type <SIntVal> INTVAL
1774 %token <FPVal> FPVAL // Float or Double constant
1776 // Built in types...
1777 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1778 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1779 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1780 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1782 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1783 %type <StrVal> Name OptName OptAssign
1784 %type <UIntVal> OptAlign OptCAlign
1785 %type <StrVal> OptSection SectionString
1787 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1788 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1789 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1790 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1791 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1792 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1793 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1794 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1796 %type <UIntVal> OptCallingConv
1798 // Basic Block Terminating Operators
1799 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1800 %token UNWIND EXCEPT
1803 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1804 %type <BinaryOpVal> ShiftOps
1805 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1806 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1807 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1808 %token <OtherOpVal> ICMP FCMP
1810 // Memory Instructions
1811 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1814 %token <OtherOpVal> PHI_TOK SELECT VAARG
1815 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1816 %token VAARG_old VANEXT_old //OBSOLETE
1818 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1819 %type <IPred> IPredicates
1820 %type <FPred> FPredicates
1821 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1822 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1824 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1825 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1826 %type <CastOpVal> CastOps
1832 // Handle constant integer size restriction and conversion...
1837 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1838 error("Value too large for type");
1844 : ESINT64VAL // These have same type and can't cause problems...
1846 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1847 error("Value too large for type");
1851 // Operations that are notably excluded from this list include:
1852 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1855 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1863 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1867 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1868 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1869 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1870 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1871 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1875 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1876 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1877 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1878 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1879 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1880 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1881 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1882 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1883 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1886 : SHL | SHR | ASHR | LSHR
1890 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1891 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1894 // These are some types that allow classification if we only want a particular
1895 // thing... for example, only a signed, unsigned, or integral type.
1897 : LONG | INT | SHORT | SBYTE
1901 : ULONG | UINT | USHORT | UBYTE
1905 : SIntType | UIntType
1912 // OptAssign - Value producing statements have an optional assignment component
1922 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1923 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1924 | WEAK { $$ = GlobalValue::WeakLinkage; }
1925 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1926 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1927 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1928 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1929 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1933 : /*empty*/ { $$ = OldCallingConv::C; }
1934 | CCC_TOK { $$ = OldCallingConv::C; }
1935 | CSRETCC_TOK { $$ = OldCallingConv::CSRet; }
1936 | FASTCC_TOK { $$ = OldCallingConv::Fast; }
1937 | COLDCC_TOK { $$ = OldCallingConv::Cold; }
1938 | X86_STDCALLCC_TOK { $$ = OldCallingConv::X86_StdCall; }
1939 | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; }
1940 | CC_TOK EUINT64VAL {
1941 if ((unsigned)$2 != $2)
1942 error("Calling conv too large");
1947 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1948 // a comma before it.
1950 : /*empty*/ { $$ = 0; }
1951 | ALIGN EUINT64VAL {
1953 if ($$ != 0 && !isPowerOf2_32($$))
1954 error("Alignment must be a power of two");
1959 : /*empty*/ { $$ = 0; }
1960 | ',' ALIGN EUINT64VAL {
1962 if ($$ != 0 && !isPowerOf2_32($$))
1963 error("Alignment must be a power of two");
1968 : SECTION STRINGCONSTANT {
1969 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1970 if ($2[i] == '"' || $2[i] == '\\')
1971 error("Invalid character in section name");
1977 : /*empty*/ { $$ = 0; }
1978 | SectionString { $$ = $1; }
1981 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1982 // is set to be the global we are processing.
1986 | ',' GlobalVarAttribute GlobalVarAttributes {}
1991 CurGV->setSection($1);
1994 | ALIGN EUINT64VAL {
1995 if ($2 != 0 && !isPowerOf2_32($2))
1996 error("Alignment must be a power of two");
1997 CurGV->setAlignment($2);
2002 //===----------------------------------------------------------------------===//
2003 // Types includes all predefined types... except void, because it can only be
2004 // used in specific contexts (function returning void for example). To have
2005 // access to it, a user must explicitly use TypesV.
2008 // TypesV includes all of 'Types', but it also includes the void type.
2012 $$.PAT = new PATypeHolder($1.T);
2013 $$.S.makeSignless();
2020 $$.PAT = new PATypeHolder($1.T);
2021 $$.S.makeSignless();
2027 if (!UpRefs.empty())
2028 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
2034 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
2035 | LONG | ULONG | FLOAT | DOUBLE | LABEL
2038 // Derived types are added later...
2041 $$.PAT = new PATypeHolder($1.T);
2045 $$.PAT = new PATypeHolder(OpaqueType::get());
2046 $$.S.makeSignless();
2048 | SymbolicValueRef { // Named types are also simple types...
2049 $$.S.copy(getTypeSign($1));
2050 const Type* tmp = getType($1);
2051 $$.PAT = new PATypeHolder(tmp);
2053 | '\\' EUINT64VAL { // Type UpReference
2054 if ($2 > (uint64_t)~0U)
2055 error("Value out of range");
2056 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
2057 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
2058 $$.PAT = new PATypeHolder(OT);
2059 $$.S.makeSignless();
2060 UR_OUT("New Upreference!\n");
2062 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
2063 $$.S.makeComposite($1.S);
2064 std::vector<const Type*> Params;
2065 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2066 E = $3->end(); I != E; ++I) {
2067 Params.push_back(I->PAT->get());
2070 FunctionType::ParamAttrsList ParamAttrs;
2071 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
2072 if (isVarArg) Params.pop_back();
2074 $$.PAT = new PATypeHolder(
2075 HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg,
2076 ParamAttrs), $$.S));
2077 delete $1.PAT; // Delete the return type handle
2078 delete $3; // Delete the argument list
2080 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
2081 $$.S.makeComposite($4.S);
2082 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
2083 (unsigned)$2), $$.S));
2086 | '<' EUINT64VAL 'x' UpRTypes '>' { // Vector type?
2087 const llvm::Type* ElemTy = $4.PAT->get();
2088 if ((unsigned)$2 != $2)
2089 error("Unsigned result not equal to signed result");
2090 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
2091 error("Elements of a VectorType must be integer or floating point");
2092 if (!isPowerOf2_32($2))
2093 error("VectorType length should be a power of 2");
2094 $$.S.makeComposite($4.S);
2095 $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy,
2096 (unsigned)$2), $$.S));
2099 | '{' TypeListI '}' { // Structure type?
2100 std::vector<const Type*> Elements;
2101 $$.S.makeComposite();
2102 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
2103 E = $2->end(); I != E; ++I) {
2104 Elements.push_back(I->PAT->get());
2107 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements), $$.S));
2110 | '{' '}' { // Empty structure type?
2111 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
2112 $$.S.makeComposite();
2114 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
2115 $$.S.makeComposite();
2116 std::vector<const Type*> Elements;
2117 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2118 E = $3->end(); I != E; ++I) {
2119 Elements.push_back(I->PAT->get());
2123 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true),
2127 | '<' '{' '}' '>' { // Empty packed structure type?
2128 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
2129 $$.S.makeComposite();
2131 | UpRTypes '*' { // Pointer type?
2132 if ($1.PAT->get() == Type::LabelTy)
2133 error("Cannot form a pointer to a basic block");
2134 $$.S.makeComposite($1.S);
2135 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get()),
2141 // TypeList - Used for struct declarations and as a basis for function type
2142 // declaration type lists
2146 $$ = new std::list<PATypeInfo>();
2149 | TypeListI ',' UpRTypes {
2150 ($$=$1)->push_back($3);
2154 // ArgTypeList - List of types for a function type declaration...
2157 | TypeListI ',' DOTDOTDOT {
2159 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2160 VoidTI.S.makeSignless();
2161 ($$=$1)->push_back(VoidTI);
2164 $$ = new std::list<PATypeInfo>();
2166 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2167 VoidTI.S.makeSignless();
2168 $$->push_back(VoidTI);
2171 $$ = new std::list<PATypeInfo>();
2175 // ConstVal - The various declarations that go into the constant pool. This
2176 // production is used ONLY to represent constants that show up AFTER a 'const',
2177 // 'constant' or 'global' token at global scope. Constants that can be inlined
2178 // into other expressions (such as integers and constexprs) are handled by the
2179 // ResolvedVal, ValueRef and ConstValueRef productions.
2182 : Types '[' ConstVector ']' { // Nonempty unsized arr
2183 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2185 error("Cannot make array constant with type: '" +
2186 $1.PAT->get()->getDescription() + "'");
2187 const Type *ETy = ATy->getElementType();
2188 int NumElements = ATy->getNumElements();
2190 // Verify that we have the correct size...
2191 if (NumElements != -1 && NumElements != (int)$3->size())
2192 error("Type mismatch: constant sized array initialized with " +
2193 utostr($3->size()) + " arguments, but has size of " +
2194 itostr(NumElements) + "");
2196 // Verify all elements are correct type!
2197 std::vector<Constant*> Elems;
2198 for (unsigned i = 0; i < $3->size(); i++) {
2199 Constant *C = (*$3)[i].C;
2200 const Type* ValTy = C->getType();
2202 error("Element #" + utostr(i) + " is not of type '" +
2203 ETy->getDescription() +"' as required!\nIt is of type '"+
2204 ValTy->getDescription() + "'");
2207 $$.C = ConstantArray::get(ATy, Elems);
2213 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2215 error("Cannot make array constant with type: '" +
2216 $1.PAT->get()->getDescription() + "'");
2217 int NumElements = ATy->getNumElements();
2218 if (NumElements != -1 && NumElements != 0)
2219 error("Type mismatch: constant sized array initialized with 0"
2220 " arguments, but has size of " + itostr(NumElements) +"");
2221 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
2225 | Types 'c' STRINGCONSTANT {
2226 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2228 error("Cannot make array constant with type: '" +
2229 $1.PAT->get()->getDescription() + "'");
2230 int NumElements = ATy->getNumElements();
2231 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2232 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2233 error("String arrays require type i8, not '" + ETy->getDescription() +
2235 char *EndStr = UnEscapeLexed($3, true);
2236 if (NumElements != -1 && NumElements != (EndStr-$3))
2237 error("Can't build string constant of size " +
2238 itostr((int)(EndStr-$3)) + " when array has size " +
2239 itostr(NumElements) + "");
2240 std::vector<Constant*> Vals;
2241 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2242 Vals.push_back(ConstantInt::get(ETy, *C));
2244 $$.C = ConstantArray::get(ATy, Vals);
2248 | Types '<' ConstVector '>' { // Nonempty unsized arr
2249 const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2251 error("Cannot make packed constant with type: '" +
2252 $1.PAT->get()->getDescription() + "'");
2253 const Type *ETy = PTy->getElementType();
2254 int NumElements = PTy->getNumElements();
2255 // Verify that we have the correct size...
2256 if (NumElements != -1 && NumElements != (int)$3->size())
2257 error("Type mismatch: constant sized packed initialized with " +
2258 utostr($3->size()) + " arguments, but has size of " +
2259 itostr(NumElements) + "");
2260 // Verify all elements are correct type!
2261 std::vector<Constant*> Elems;
2262 for (unsigned i = 0; i < $3->size(); i++) {
2263 Constant *C = (*$3)[i].C;
2264 const Type* ValTy = C->getType();
2266 error("Element #" + utostr(i) + " is not of type '" +
2267 ETy->getDescription() +"' as required!\nIt is of type '"+
2268 ValTy->getDescription() + "'");
2271 $$.C = ConstantVector::get(PTy, Elems);
2276 | Types '{' ConstVector '}' {
2277 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2279 error("Cannot make struct constant with type: '" +
2280 $1.PAT->get()->getDescription() + "'");
2281 if ($3->size() != STy->getNumContainedTypes())
2282 error("Illegal number of initializers for structure type");
2284 // Check to ensure that constants are compatible with the type initializer!
2285 std::vector<Constant*> Fields;
2286 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2287 Constant *C = (*$3)[i].C;
2288 if (C->getType() != STy->getElementType(i))
2289 error("Expected type '" + STy->getElementType(i)->getDescription() +
2290 "' for element #" + utostr(i) + " of structure initializer");
2291 Fields.push_back(C);
2293 $$.C = ConstantStruct::get(STy, Fields);
2299 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2301 error("Cannot make struct constant with type: '" +
2302 $1.PAT->get()->getDescription() + "'");
2303 if (STy->getNumContainedTypes() != 0)
2304 error("Illegal number of initializers for structure type");
2305 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2309 | Types '<' '{' ConstVector '}' '>' {
2310 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2312 error("Cannot make packed struct constant with type: '" +
2313 $1.PAT->get()->getDescription() + "'");
2314 if ($4->size() != STy->getNumContainedTypes())
2315 error("Illegal number of initializers for packed structure type");
2317 // Check to ensure that constants are compatible with the type initializer!
2318 std::vector<Constant*> Fields;
2319 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2320 Constant *C = (*$4)[i].C;
2321 if (C->getType() != STy->getElementType(i))
2322 error("Expected type '" + STy->getElementType(i)->getDescription() +
2323 "' for element #" + utostr(i) + " of packed struct initializer");
2324 Fields.push_back(C);
2326 $$.C = ConstantStruct::get(STy, Fields);
2331 | Types '<' '{' '}' '>' {
2332 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2334 error("Cannot make packed struct constant with type: '" +
2335 $1.PAT->get()->getDescription() + "'");
2336 if (STy->getNumContainedTypes() != 0)
2337 error("Illegal number of initializers for packed structure type");
2338 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2343 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2345 error("Cannot make null pointer constant with type: '" +
2346 $1.PAT->get()->getDescription() + "'");
2347 $$.C = ConstantPointerNull::get(PTy);
2352 $$.C = UndefValue::get($1.PAT->get());
2356 | Types SymbolicValueRef {
2357 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2359 error("Global const reference must be a pointer type, not" +
2360 $1.PAT->get()->getDescription());
2362 // ConstExprs can exist in the body of a function, thus creating
2363 // GlobalValues whenever they refer to a variable. Because we are in
2364 // the context of a function, getExistingValue will search the functions
2365 // symbol table instead of the module symbol table for the global symbol,
2366 // which throws things all off. To get around this, we just tell
2367 // getExistingValue that we are at global scope here.
2369 Function *SavedCurFn = CurFun.CurrentFunction;
2370 CurFun.CurrentFunction = 0;
2372 Value *V = getExistingValue(Ty, $2);
2373 CurFun.CurrentFunction = SavedCurFn;
2375 // If this is an initializer for a constant pointer, which is referencing a
2376 // (currently) undefined variable, create a stub now that shall be replaced
2377 // in the future with the right type of variable.
2380 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2381 const PointerType *PT = cast<PointerType>(Ty);
2383 // First check to see if the forward references value is already created!
2384 PerModuleInfo::GlobalRefsType::iterator I =
2385 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2387 if (I != CurModule.GlobalRefs.end()) {
2388 V = I->second; // Placeholder already exists, use it...
2392 if ($2.Type == ValID::NameVal) Name = $2.Name;
2394 // Create the forward referenced global.
2396 if (const FunctionType *FTy =
2397 dyn_cast<FunctionType>(PT->getElementType())) {
2398 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2399 CurModule.CurrentModule);
2401 GV = new GlobalVariable(PT->getElementType(), false,
2402 GlobalValue::ExternalLinkage, 0,
2403 Name, CurModule.CurrentModule);
2406 // Keep track of the fact that we have a forward ref to recycle it
2407 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2411 $$.C = cast<GlobalValue>(V);
2413 delete $1.PAT; // Free the type handle
2416 if ($1.PAT->get() != $2.C->getType())
2417 error("Mismatched types for constant expression");
2422 | Types ZEROINITIALIZER {
2423 const Type *Ty = $1.PAT->get();
2424 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2425 error("Cannot create a null initialized value of this type");
2426 $$.C = Constant::getNullValue(Ty);
2430 | SIntType EINT64VAL { // integral constants
2431 const Type *Ty = $1.T;
2432 if (!ConstantInt::isValueValidForType(Ty, $2))
2433 error("Constant value doesn't fit in type");
2434 $$.C = ConstantInt::get(Ty, $2);
2437 | UIntType EUINT64VAL { // integral constants
2438 const Type *Ty = $1.T;
2439 if (!ConstantInt::isValueValidForType(Ty, $2))
2440 error("Constant value doesn't fit in type");
2441 $$.C = ConstantInt::get(Ty, $2);
2442 $$.S.makeUnsigned();
2444 | BOOL TRUETOK { // Boolean constants
2445 $$.C = ConstantInt::get(Type::Int1Ty, true);
2446 $$.S.makeUnsigned();
2448 | BOOL FALSETOK { // Boolean constants
2449 $$.C = ConstantInt::get(Type::Int1Ty, false);
2450 $$.S.makeUnsigned();
2452 | FPType FPVAL { // Float & Double constants
2453 if (!ConstantFP::isValueValidForType($1.T, $2))
2454 error("Floating point constant invalid for type");
2455 $$.C = ConstantFP::get($1.T, $2);
2456 $$.S.makeSignless();
2461 : CastOps '(' ConstVal TO Types ')' {
2462 const Type* SrcTy = $3.C->getType();
2463 const Type* DstTy = $5.PAT->get();
2464 Signedness SrcSign($3.S);
2465 Signedness DstSign($5.S);
2466 if (!SrcTy->isFirstClassType())
2467 error("cast constant expression from a non-primitive type: '" +
2468 SrcTy->getDescription() + "'");
2469 if (!DstTy->isFirstClassType())
2470 error("cast constant expression to a non-primitive type: '" +
2471 DstTy->getDescription() + "'");
2472 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2476 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2477 const Type *Ty = $3.C->getType();
2478 if (!isa<PointerType>(Ty))
2479 error("GetElementPtr requires a pointer operand");
2481 std::vector<Value*> VIndices;
2482 std::vector<Constant*> CIndices;
2483 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2486 $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2487 $$.S.copy(getElementSign($3, CIndices));
2489 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2490 if (!$3.C->getType()->isInteger() ||
2491 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2492 error("Select condition must be bool type");
2493 if ($5.C->getType() != $7.C->getType())
2494 error("Select operand types must match");
2495 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2498 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2499 const Type *Ty = $3.C->getType();
2500 if (Ty != $5.C->getType())
2501 error("Binary operator types must match");
2502 // First, make sure we're dealing with the right opcode by upgrading from
2503 // obsolete versions.
2504 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2506 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2507 // To retain backward compatibility with these early compilers, we emit a
2508 // cast to the appropriate integer type automatically if we are in the
2509 // broken case. See PR424 for more information.
2510 if (!isa<PointerType>(Ty)) {
2511 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2513 const Type *IntPtrTy = 0;
2514 switch (CurModule.CurrentModule->getPointerSize()) {
2515 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2516 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2517 default: error("invalid pointer binary constant expr");
2519 $$.C = ConstantExpr::get(Opcode,
2520 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2521 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2522 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2526 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2527 const Type* Ty = $3.C->getType();
2528 if (Ty != $5.C->getType())
2529 error("Logical operator types must match");
2530 if (!Ty->isInteger()) {
2531 if (!isa<VectorType>(Ty) ||
2532 !cast<VectorType>(Ty)->getElementType()->isInteger())
2533 error("Logical operator requires integer operands");
2535 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2536 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2539 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2540 const Type* Ty = $3.C->getType();
2541 if (Ty != $5.C->getType())
2542 error("setcc operand types must match");
2543 unsigned short pred;
2544 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2545 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2546 $$.S.makeUnsigned();
2548 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2549 if ($4.C->getType() != $6.C->getType())
2550 error("icmp operand types must match");
2551 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2552 $$.S.makeUnsigned();
2554 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2555 if ($4.C->getType() != $6.C->getType())
2556 error("fcmp operand types must match");
2557 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2558 $$.S.makeUnsigned();
2560 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2561 if (!$5.C->getType()->isInteger() ||
2562 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2563 error("Shift count for shift constant must be unsigned byte");
2564 const Type* Ty = $3.C->getType();
2565 if (!$3.C->getType()->isInteger())
2566 error("Shift constant expression requires integer operand");
2567 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2568 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2571 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2572 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2573 error("Invalid extractelement operands");
2574 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2575 $$.S.copy($3.S.get(0));
2577 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2578 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2579 error("Invalid insertelement operands");
2580 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2583 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2584 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2585 error("Invalid shufflevector operands");
2586 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2592 // ConstVector - A list of comma separated constants.
2594 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2596 $$ = new std::vector<ConstInfo>();
2602 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2604 : GLOBAL { $$ = false; }
2605 | CONSTANT { $$ = true; }
2609 //===----------------------------------------------------------------------===//
2610 // Rules to match Modules
2611 //===----------------------------------------------------------------------===//
2613 // Module rule: Capture the result of parsing the whole file into a result
2618 $$ = ParserResult = $1;
2619 CurModule.ModuleDone();
2623 // FunctionList - A list of functions, preceeded by a constant pool.
2626 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2627 | FunctionList FunctionProto { $$ = $1; }
2628 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2629 | FunctionList IMPLEMENTATION { $$ = $1; }
2631 $$ = CurModule.CurrentModule;
2632 // Emit an error if there are any unresolved types left.
2633 if (!CurModule.LateResolveTypes.empty()) {
2634 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2635 if (DID.Type == ValID::NameVal) {
2636 error("Reference to an undefined type: '"+DID.getName() + "'");
2638 error("Reference to an undefined type: #" + itostr(DID.Num));
2644 // ConstPool - Constants with optional names assigned to them.
2646 : ConstPool OptAssign TYPE TypesV {
2647 // Eagerly resolve types. This is not an optimization, this is a
2648 // requirement that is due to the fact that we could have this:
2650 // %list = type { %list * }
2651 // %list = type { %list * } ; repeated type decl
2653 // If types are not resolved eagerly, then the two types will not be
2654 // determined to be the same type!
2656 ResolveTypeTo($2, $4.PAT->get(), $4.S);
2658 if (!setTypeName($4, $2) && !$2) {
2659 // If this is a numbered type that is not a redefinition, add it to the
2661 CurModule.Types.push_back($4.PAT->get());
2662 CurModule.TypeSigns.push_back($4.S);
2666 | ConstPool FunctionProto { // Function prototypes can be in const pool
2668 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2670 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2672 error("Global value initializer is not a constant");
2673 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2674 } GlobalVarAttributes {
2677 | ConstPool OptAssign EXTERNAL GlobalType Types {
2678 const Type *Ty = $5.PAT->get();
2679 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2682 } GlobalVarAttributes {
2685 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2686 const Type *Ty = $5.PAT->get();
2687 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2690 } GlobalVarAttributes {
2693 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2694 const Type *Ty = $5.PAT->get();
2696 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0,
2699 } GlobalVarAttributes {
2702 | ConstPool TARGET TargetDefinition {
2704 | ConstPool DEPLIBS '=' LibrariesDefinition {
2706 | /* empty: end of list */ {
2712 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2713 char *EndStr = UnEscapeLexed($1, true);
2714 std::string NewAsm($1, EndStr);
2717 if (AsmSoFar.empty())
2718 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2720 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2725 : BIG { $$ = Module::BigEndian; }
2726 | LITTLE { $$ = Module::LittleEndian; }
2730 : ENDIAN '=' BigOrLittle {
2731 CurModule.setEndianness($3);
2733 | POINTERSIZE '=' EUINT64VAL {
2735 CurModule.setPointerSize(Module::Pointer32);
2737 CurModule.setPointerSize(Module::Pointer64);
2739 error("Invalid pointer size: '" + utostr($3) + "'");
2741 | TRIPLE '=' STRINGCONSTANT {
2742 CurModule.CurrentModule->setTargetTriple($3);
2745 | DATALAYOUT '=' STRINGCONSTANT {
2746 CurModule.CurrentModule->setDataLayout($3);
2756 : LibList ',' STRINGCONSTANT {
2757 CurModule.CurrentModule->addLibrary($3);
2761 CurModule.CurrentModule->addLibrary($1);
2764 | /* empty: end of list */ { }
2767 //===----------------------------------------------------------------------===//
2768 // Rules to match Function Headers
2769 //===----------------------------------------------------------------------===//
2772 : VAR_ID | STRINGCONSTANT
2777 | /*empty*/ { $$ = 0; }
2782 if ($1.PAT->get() == Type::VoidTy)
2783 error("void typed arguments are invalid");
2784 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2789 : ArgListH ',' ArgVal {
2795 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2802 : ArgListH { $$ = $1; }
2803 | ArgListH ',' DOTDOTDOT {
2806 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2807 VoidTI.S.makeSignless();
2808 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2811 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2813 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2814 VoidTI.S.makeSignless();
2815 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2817 | /* empty */ { $$ = 0; }
2821 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2823 std::string FunctionName($3);
2824 free($3); // Free strdup'd memory!
2826 const Type* RetTy = $2.PAT->get();
2828 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2829 error("LLVM functions cannot return aggregate types");
2832 FTySign.makeComposite($2.S);
2833 std::vector<const Type*> ParamTyList;
2835 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2836 // i8*. We check here for those names and override the parameter list
2837 // types to ensure the prototype is correct.
2838 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2839 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2840 } else if (FunctionName == "llvm.va_copy") {
2841 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2842 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2843 } else if ($5) { // If there are arguments...
2844 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2845 I = $5->begin(), E = $5->end(); I != E; ++I) {
2846 const Type *Ty = I->first.PAT->get();
2847 ParamTyList.push_back(Ty);
2848 FTySign.add(I->first.S);
2852 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2854 ParamTyList.pop_back();
2856 // Convert the CSRet calling convention into the corresponding parameter
2858 FunctionType::ParamAttrsList ParamAttrs;
2859 if ($1 == OldCallingConv::CSRet) {
2860 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2861 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2864 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
2866 const PointerType *PFT = PointerType::get(FT);
2870 if (!FunctionName.empty()) {
2871 ID = ValID::create((char*)FunctionName.c_str());
2873 ID = ValID::create((int)CurModule.Values[PFT].size());
2875 ID.S.makeComposite(FTySign);
2878 Module* M = CurModule.CurrentModule;
2880 // See if this function was forward referenced. If so, recycle the object.
2881 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2882 // Move the function to the end of the list, from whereever it was
2883 // previously inserted.
2884 Fn = cast<Function>(FWRef);
2885 M->getFunctionList().remove(Fn);
2886 M->getFunctionList().push_back(Fn);
2887 } else if (!FunctionName.empty()) {
2888 GlobalValue *Conflict = M->getFunction(FunctionName);
2890 Conflict = M->getNamedGlobal(FunctionName);
2891 if (Conflict && PFT == Conflict->getType()) {
2892 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2893 // We have two function definitions that conflict, same type, same
2894 // name. We should really check to make sure that this is the result
2895 // of integer type planes collapsing and generate an error if it is
2896 // not, but we'll just rename on the assumption that it is. However,
2897 // let's do it intelligently and rename the internal linkage one
2899 std::string NewName(makeNameUnique(FunctionName));
2900 if (Conflict->hasInternalLinkage()) {
2901 Conflict->setName(NewName);
2903 makeRenameMapKey(FunctionName, Conflict->getType(), ID.S);
2904 CurModule.RenameMap[Key] = NewName;
2905 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2906 InsertValue(Fn, CurModule.Values);
2908 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2909 InsertValue(Fn, CurModule.Values);
2911 makeRenameMapKey(FunctionName, PFT, ID.S);
2912 CurModule.RenameMap[Key] = NewName;
2915 // If they are not both definitions, then just use the function we
2916 // found since the types are the same.
2917 Fn = cast<Function>(Conflict);
2919 // Make sure to strip off any argument names so we can't get
2921 if (Fn->isDeclaration())
2922 for (Function::arg_iterator AI = Fn->arg_begin(),
2923 AE = Fn->arg_end(); AI != AE; ++AI)
2926 } else if (Conflict) {
2927 // We have two globals with the same name and different types.
2928 // Previously, this was permitted because the symbol table had
2929 // "type planes" and names only needed to be distinct within a
2930 // type plane. After PR411 was fixed, this is no loner the case.
2931 // To resolve this we must rename one of the two.
2932 if (Conflict->hasInternalLinkage()) {
2933 // We can safely rename the Conflict.
2935 makeRenameMapKey(Conflict->getName(), Conflict->getType(),
2936 CurModule.NamedValueSigns[Conflict->getName()]);
2937 Conflict->setName(makeNameUnique(Conflict->getName()));
2938 CurModule.RenameMap[Key] = Conflict->getName();
2939 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2940 InsertValue(Fn, CurModule.Values);
2942 // We can't quietly rename either of these things, but we must
2943 // rename one of them. Only if the function's linkage is internal can
2944 // we forgo a warning message about the renamed function.
2945 std::string NewName = makeNameUnique(FunctionName);
2946 if (CurFun.Linkage != GlobalValue::InternalLinkage) {
2947 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2948 "' may cause linkage errors");
2950 // Elect to rename the thing we're now defining.
2951 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2952 InsertValue(Fn, CurModule.Values);
2953 RenameMapKey Key = makeRenameMapKey(FunctionName, PFT, ID.S);
2954 CurModule.RenameMap[Key] = NewName;
2957 // There's no conflict, just define the function
2958 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2959 InsertValue(Fn, CurModule.Values);
2963 CurFun.FunctionStart(Fn);
2965 if (CurFun.isDeclare) {
2966 // If we have declaration, always overwrite linkage. This will allow us
2967 // to correctly handle cases, when pointer to function is passed as
2968 // argument to another function.
2969 Fn->setLinkage(CurFun.Linkage);
2971 Fn->setCallingConv(upgradeCallingConv($1));
2972 Fn->setAlignment($8);
2978 // Add all of the arguments we parsed to the function...
2979 if ($5) { // Is null if empty...
2980 if (isVarArg) { // Nuke the last entry
2981 assert($5->back().first.PAT->get() == Type::VoidTy &&
2982 $5->back().second == 0 && "Not a varargs marker");
2983 delete $5->back().first.PAT;
2984 $5->pop_back(); // Delete the last entry
2986 Function::arg_iterator ArgIt = Fn->arg_begin();
2987 Function::arg_iterator ArgEnd = Fn->arg_end();
2988 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2989 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2990 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2991 delete I->first.PAT; // Delete the typeholder...
2992 ValueInfo VI; VI.V = ArgIt; VI.S.copy(I->first.S);
2993 setValueName(VI, I->second); // Insert arg into symtab...
2996 delete $5; // We're now done with the argument list
3002 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
3006 : OptLinkage { CurFun.Linkage = $1; } FunctionHeaderH BEGIN {
3007 $$ = CurFun.CurrentFunction;
3009 // Make sure that we keep track of the linkage type even if there was a
3010 // previous "declare".
3016 : ENDTOK | '}' // Allow end of '}' to end a function
3020 : BasicBlockList END {
3025 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
3026 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
3027 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
3031 : DECLARE { CurFun.isDeclare = true; }
3032 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
3033 $$ = CurFun.CurrentFunction;
3034 CurFun.FunctionDone();
3039 //===----------------------------------------------------------------------===//
3040 // Rules to match Basic Blocks
3041 //===----------------------------------------------------------------------===//
3044 : /* empty */ { $$ = false; }
3045 | SIDEEFFECT { $$ = true; }
3049 // A reference to a direct constant
3050 : ESINT64VAL { $$ = ValID::create($1); }
3051 | EUINT64VAL { $$ = ValID::create($1); }
3052 | FPVAL { $$ = ValID::create($1); }
3054 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true));
3055 $$.S.makeUnsigned();
3058 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false));
3059 $$.S.makeUnsigned();
3061 | NULL_TOK { $$ = ValID::createNull(); }
3062 | UNDEF { $$ = ValID::createUndef(); }
3063 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
3064 | '<' ConstVector '>' { // Nonempty unsized packed vector
3065 const Type *ETy = (*$2)[0].C->getType();
3066 int NumElements = $2->size();
3067 VectorType* pt = VectorType::get(ETy, NumElements);
3068 $$.S.makeComposite((*$2)[0].S);
3069 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt, $$.S));
3071 // Verify all elements are correct type!
3072 std::vector<Constant*> Elems;
3073 for (unsigned i = 0; i < $2->size(); i++) {
3074 Constant *C = (*$2)[i].C;
3075 const Type *CTy = C->getType();
3077 error("Element #" + utostr(i) + " is not of type '" +
3078 ETy->getDescription() +"' as required!\nIt is of type '" +
3079 CTy->getDescription() + "'");
3082 $$ = ValID::create(ConstantVector::get(pt, Elems));
3083 delete PTy; delete $2;
3086 $$ = ValID::create($1.C);
3089 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
3090 char *End = UnEscapeLexed($3, true);
3091 std::string AsmStr = std::string($3, End);
3092 End = UnEscapeLexed($5, true);
3093 std::string Constraints = std::string($5, End);
3094 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
3100 // SymbolicValueRef - Reference to one of two ways of symbolically refering to // another value.
3103 : INTVAL { $$ = ValID::create($1); $$.S.makeSignless(); }
3104 | Name { $$ = ValID::create($1); $$.S.makeSignless(); }
3107 // ValueRef - A reference to a definition... either constant or symbolic
3109 : SymbolicValueRef | ConstValueRef
3113 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
3114 // type immediately preceeds the value reference, and allows complex constant
3115 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
3118 const Type *Ty = $1.PAT->get();
3120 $$.V = getVal(Ty, $2);
3127 : BasicBlockList BasicBlock {
3130 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
3135 // Basic blocks are terminated by branching instructions:
3136 // br, br/cc, switch, ret
3139 : InstructionList OptAssign BBTerminatorInst {
3140 ValueInfo VI; VI.V = $3.TI; VI.S.copy($3.S);
3141 setValueName(VI, $2);
3143 $1->getInstList().push_back($3.TI);
3150 : InstructionList Inst {
3152 $1->getInstList().push_back($2.I);
3156 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++),true);
3157 // Make sure to move the basic block to the correct location in the
3158 // function, instead of leaving it inserted wherever it was first
3160 Function::BasicBlockListType &BBL =
3161 CurFun.CurrentFunction->getBasicBlockList();
3162 BBL.splice(BBL.end(), BBL, $$);
3165 $$ = CurBB = getBBVal(ValID::create($1), true);
3166 // Make sure to move the basic block to the correct location in the
3167 // function, instead of leaving it inserted wherever it was first
3169 Function::BasicBlockListType &BBL =
3170 CurFun.CurrentFunction->getBasicBlockList();
3171 BBL.splice(BBL.end(), BBL, $$);
3175 Unwind : UNWIND | EXCEPT;
3178 : RET ResolvedVal { // Return with a result...
3179 $$.TI = new ReturnInst($2.V);
3180 $$.S.makeSignless();
3182 | RET VOID { // Return with no result...
3183 $$.TI = new ReturnInst();
3184 $$.S.makeSignless();
3186 | BR LABEL ValueRef { // Unconditional Branch...
3187 BasicBlock* tmpBB = getBBVal($3);
3188 $$.TI = new BranchInst(tmpBB);
3189 $$.S.makeSignless();
3190 } // Conditional Branch...
3191 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
3192 $6.S.makeSignless();
3193 $9.S.makeSignless();
3194 BasicBlock* tmpBBA = getBBVal($6);
3195 BasicBlock* tmpBBB = getBBVal($9);
3196 $3.S.makeUnsigned();
3197 Value* tmpVal = getVal(Type::Int1Ty, $3);
3198 $$.TI = new BranchInst(tmpBBA, tmpBBB, tmpVal);
3199 $$.S.makeSignless();
3201 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
3203 Value* tmpVal = getVal($2.T, $3);
3204 $6.S.makeSignless();
3205 BasicBlock* tmpBB = getBBVal($6);
3206 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
3208 $$.S.makeSignless();
3209 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
3211 for (; I != E; ++I) {
3212 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
3213 S->addCase(CI, I->second);
3215 error("Switch case is constant, but not a simple integer");
3219 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
3221 Value* tmpVal = getVal($2.T, $3);
3222 $6.S.makeSignless();
3223 BasicBlock* tmpBB = getBBVal($6);
3224 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
3226 $$.S.makeSignless();
3228 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
3229 TO LABEL ValueRef Unwind LABEL ValueRef {
3230 const PointerType *PFTy;
3231 const FunctionType *Ty;
3234 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3235 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3236 // Pull out the types of all of the arguments...
3237 std::vector<const Type*> ParamTypes;
3238 FTySign.makeComposite($3.S);
3240 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3242 ParamTypes.push_back((*I).V->getType());
3246 FunctionType::ParamAttrsList ParamAttrs;
3247 if ($2 == OldCallingConv::CSRet) {
3248 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3249 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3251 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3252 if (isVarArg) ParamTypes.pop_back();
3253 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
3254 PFTy = PointerType::get(Ty);
3258 $$.S.copy($3.S.get(0)); // 0th element of FuncTy sign is result ty
3260 $4.S.makeComposite(FTySign);
3261 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3262 BasicBlock *Normal = getBBVal($10);
3263 BasicBlock *Except = getBBVal($13);
3265 // Create the call node...
3266 if (!$6) { // Has no arguments?
3267 $$.TI = new InvokeInst(V, Normal, Except, 0, 0);
3268 } else { // Has arguments?
3269 // Loop through FunctionType's arguments and ensure they are specified
3272 FunctionType::param_iterator I = Ty->param_begin();
3273 FunctionType::param_iterator E = Ty->param_end();
3274 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3276 std::vector<Value*> Args;
3277 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3278 if ((*ArgI).V->getType() != *I)
3279 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3280 (*I)->getDescription() + "'");
3281 Args.push_back((*ArgI).V);
3284 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3285 error("Invalid number of parameters detected");
3287 $$.TI = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
3289 cast<InvokeInst>($$.TI)->setCallingConv(upgradeCallingConv($2));
3294 $$.TI = new UnwindInst();
3295 $$.S.makeSignless();
3298 $$.TI = new UnreachableInst();
3299 $$.S.makeSignless();
3304 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3307 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3310 error("May only switch on a constant pool value");
3312 $6.S.makeSignless();
3313 BasicBlock* tmpBB = getBBVal($6);
3314 $$->push_back(std::make_pair(V, tmpBB));
3316 | IntType ConstValueRef ',' LABEL ValueRef {
3317 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3319 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3322 error("May only switch on a constant pool value");
3324 $5.S.makeSignless();
3325 BasicBlock* tmpBB = getBBVal($5);
3326 $$->push_back(std::make_pair(V, tmpBB));
3331 : OptAssign InstVal {
3334 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3335 if (BCI->getSrcTy() == BCI->getDestTy() &&
3336 BCI->getOperand(0)->getName() == $1)
3337 // This is a useless bit cast causing a name redefinition. It is
3338 // a bit cast from a type to the same type of an operand with the
3339 // same name as the name we would give this instruction. Since this
3340 // instruction results in no code generation, it is safe to omit
3341 // the instruction. This situation can occur because of collapsed
3342 // type planes. For example:
3343 // %X = add int %Y, %Z
3344 // %X = cast int %Y to uint
3345 // After upgrade, this looks like:
3346 // %X = add i32 %Y, %Z
3347 // %X = bitcast i32 to i32
3348 // The bitcast is clearly useless so we omit it.
3352 $$.S.makeSignless();
3354 ValueInfo VI; VI.V = $2.I; VI.S.copy($2.S);
3355 setValueName(VI, $1);
3361 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3362 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3365 Value* tmpVal = getVal($1.PAT->get(), $3);
3366 $5.S.makeSignless();
3367 BasicBlock* tmpBB = getBBVal($5);
3368 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3371 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3374 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3375 $6.S.makeSignless();
3376 BasicBlock* tmpBB = getBBVal($6);
3377 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3381 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3382 $$ = new std::vector<ValueInfo>();
3385 | ValueRefList ',' ResolvedVal {
3390 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3393 | /*empty*/ { $$ = 0; }
3406 : ArithmeticOps Types ValueRef ',' ValueRef {
3409 const Type* Ty = $2.PAT->get();
3410 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3411 error("Arithmetic operator requires integer, FP, or packed operands");
3412 if (isa<VectorType>(Ty) &&
3413 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3414 error("Remainder not supported on vector types");
3415 // Upgrade the opcode from obsolete versions before we do anything with it.
3416 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3417 Value* val1 = getVal(Ty, $3);
3418 Value* val2 = getVal(Ty, $5);
3419 $$.I = BinaryOperator::create(Opcode, val1, val2);
3421 error("binary operator returned null");
3425 | LogicalOps Types ValueRef ',' ValueRef {
3428 const Type *Ty = $2.PAT->get();
3429 if (!Ty->isInteger()) {
3430 if (!isa<VectorType>(Ty) ||
3431 !cast<VectorType>(Ty)->getElementType()->isInteger())
3432 error("Logical operator requires integral operands");
3434 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3435 Value* tmpVal1 = getVal(Ty, $3);
3436 Value* tmpVal2 = getVal(Ty, $5);
3437 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3439 error("binary operator returned null");
3443 | SetCondOps Types ValueRef ',' ValueRef {
3446 const Type* Ty = $2.PAT->get();
3447 if(isa<VectorType>(Ty))
3448 error("VectorTypes currently not supported in setcc instructions");
3449 unsigned short pred;
3450 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3451 Value* tmpVal1 = getVal(Ty, $3);
3452 Value* tmpVal2 = getVal(Ty, $5);
3453 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3455 error("binary operator returned null");
3456 $$.S.makeUnsigned();
3459 | ICMP IPredicates Types ValueRef ',' ValueRef {
3462 const Type *Ty = $3.PAT->get();
3463 if (isa<VectorType>(Ty))
3464 error("VectorTypes currently not supported in icmp instructions");
3465 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3466 error("icmp requires integer or pointer typed operands");
3467 Value* tmpVal1 = getVal(Ty, $4);
3468 Value* tmpVal2 = getVal(Ty, $6);
3469 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3470 $$.S.makeUnsigned();
3473 | FCMP FPredicates Types ValueRef ',' ValueRef {
3476 const Type *Ty = $3.PAT->get();
3477 if (isa<VectorType>(Ty))
3478 error("VectorTypes currently not supported in fcmp instructions");
3479 else if (!Ty->isFloatingPoint())
3480 error("fcmp instruction requires floating point operands");
3481 Value* tmpVal1 = getVal(Ty, $4);
3482 Value* tmpVal2 = getVal(Ty, $6);
3483 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3484 $$.S.makeUnsigned();
3488 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3489 const Type *Ty = $2.V->getType();
3490 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3492 error("Expected integral type for not instruction");
3493 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3495 error("Could not create a xor instruction");
3498 | ShiftOps ResolvedVal ',' ResolvedVal {
3499 if (!$4.V->getType()->isInteger() ||
3500 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3501 error("Shift amount must be int8");
3502 const Type* Ty = $2.V->getType();
3503 if (!Ty->isInteger())
3504 error("Shift constant expression requires integer operand");
3505 Value* ShiftAmt = 0;
3506 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3507 if (Constant *C = dyn_cast<Constant>($4.V))
3508 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3510 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3513 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3516 | CastOps ResolvedVal TO Types {
3517 const Type *DstTy = $4.PAT->get();
3518 if (!DstTy->isFirstClassType())
3519 error("cast instruction to a non-primitive type: '" +
3520 DstTy->getDescription() + "'");
3521 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3525 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3526 if (!$2.V->getType()->isInteger() ||
3527 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3528 error("select condition must be bool");
3529 if ($4.V->getType() != $6.V->getType())
3530 error("select value types should match");
3531 $$.I = new SelectInst($2.V, $4.V, $6.V);
3534 | VAARG ResolvedVal ',' Types {
3535 const Type *Ty = $4.PAT->get();
3537 $$.I = new VAArgInst($2.V, Ty);
3541 | VAARG_old ResolvedVal ',' Types {
3542 const Type* ArgTy = $2.V->getType();
3543 const Type* DstTy = $4.PAT->get();
3544 ObsoleteVarArgs = true;
3545 Function* NF = cast<Function>(CurModule.CurrentModule->
3546 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3549 //foo = alloca 1 of t
3553 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3554 CurBB->getInstList().push_back(foo);
3555 CallInst* bar = new CallInst(NF, $2.V);
3556 CurBB->getInstList().push_back(bar);
3557 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3558 $$.I = new VAArgInst(foo, DstTy);
3562 | VANEXT_old ResolvedVal ',' Types {
3563 const Type* ArgTy = $2.V->getType();
3564 const Type* DstTy = $4.PAT->get();
3565 ObsoleteVarArgs = true;
3566 Function* NF = cast<Function>(CurModule.CurrentModule->
3567 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3569 //b = vanext a, t ->
3570 //foo = alloca 1 of t
3573 //tmp = vaarg foo, t
3575 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3576 CurBB->getInstList().push_back(foo);
3577 CallInst* bar = new CallInst(NF, $2.V);
3578 CurBB->getInstList().push_back(bar);
3579 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3580 Instruction* tmp = new VAArgInst(foo, DstTy);
3581 CurBB->getInstList().push_back(tmp);
3582 $$.I = new LoadInst(foo);
3586 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3587 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3588 error("Invalid extractelement operands");
3589 $$.I = new ExtractElementInst($2.V, $4.V);
3590 $$.S.copy($2.S.get(0));
3592 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3593 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3594 error("Invalid insertelement operands");
3595 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3598 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3599 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3600 error("Invalid shufflevector operands");
3601 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3605 const Type *Ty = $2.P->front().first->getType();
3606 if (!Ty->isFirstClassType())
3607 error("PHI node operands must be of first class type");
3608 PHINode *PHI = new PHINode(Ty);
3609 PHI->reserveOperandSpace($2.P->size());
3610 while ($2.P->begin() != $2.P->end()) {
3611 if ($2.P->front().first->getType() != Ty)
3612 error("All elements of a PHI node must be of the same type");
3613 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3618 delete $2.P; // Free the list...
3620 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3621 // Handle the short call syntax
3622 const PointerType *PFTy;
3623 const FunctionType *FTy;
3625 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3626 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3627 // Pull out the types of all of the arguments...
3628 std::vector<const Type*> ParamTypes;
3629 FTySign.makeComposite($3.S);
3631 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3633 ParamTypes.push_back((*I).V->getType());
3638 FunctionType::ParamAttrsList ParamAttrs;
3639 if ($2 == OldCallingConv::CSRet) {
3640 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3641 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3643 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3644 if (isVarArg) ParamTypes.pop_back();
3646 const Type *RetTy = $3.PAT->get();
3647 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3648 error("Functions cannot return aggregate types");
3650 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3651 PFTy = PointerType::get(FTy);
3655 $$.S.copy($3.S.get(0)); // 0th element of FuncTy signedness is result sign
3657 $4.S.makeComposite(FTySign);
3659 // First upgrade any intrinsic calls.
3660 std::vector<Value*> Args;
3662 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3663 Args.push_back((*$6)[i].V);
3664 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3666 // If we got an upgraded intrinsic
3670 // Get the function we're calling
3671 Value *V = getVal(PFTy, $4);
3673 // Check the argument values match
3674 if (!$6) { // Has no arguments?
3675 // Make sure no arguments is a good thing!
3676 if (FTy->getNumParams() != 0)
3677 error("No arguments passed to a function that expects arguments");
3678 } else { // Has arguments?
3679 // Loop through FunctionType's arguments and ensure they are specified
3682 FunctionType::param_iterator I = FTy->param_begin();
3683 FunctionType::param_iterator E = FTy->param_end();
3684 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3686 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3687 if ((*ArgI).V->getType() != *I)
3688 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3689 (*I)->getDescription() + "'");
3691 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3692 error("Invalid number of parameters detected");
3695 // Create the call instruction
3696 CallInst *CI = new CallInst(V, &Args[0], Args.size());
3697 CI->setTailCall($1);
3698 CI->setCallingConv(upgradeCallingConv($2));
3710 // IndexList - List of indices for GEP based instructions...
3712 : ',' ValueRefList { $$ = $2; }
3713 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3717 : VOLATILE { $$ = true; }
3718 | /* empty */ { $$ = false; }
3722 : MALLOC Types OptCAlign {
3723 const Type *Ty = $2.PAT->get();
3724 $$.S.makeComposite($2.S);
3725 $$.I = new MallocInst(Ty, 0, $3);
3728 | MALLOC Types ',' UINT ValueRef OptCAlign {
3729 const Type *Ty = $2.PAT->get();
3730 $5.S.makeUnsigned();
3731 $$.S.makeComposite($2.S);
3732 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3735 | ALLOCA Types OptCAlign {
3736 const Type *Ty = $2.PAT->get();
3737 $$.S.makeComposite($2.S);
3738 $$.I = new AllocaInst(Ty, 0, $3);
3741 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3742 const Type *Ty = $2.PAT->get();
3743 $5.S.makeUnsigned();
3744 $$.S.makeComposite($4.S);
3745 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3748 | FREE ResolvedVal {
3749 const Type *PTy = $2.V->getType();
3750 if (!isa<PointerType>(PTy))
3751 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3752 $$.I = new FreeInst($2.V);
3753 $$.S.makeSignless();
3755 | OptVolatile LOAD Types ValueRef {
3756 const Type* Ty = $3.PAT->get();
3758 if (!isa<PointerType>(Ty))
3759 error("Can't load from nonpointer type: " + Ty->getDescription());
3760 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3761 error("Can't load from pointer of non-first-class type: " +
3762 Ty->getDescription());
3763 Value* tmpVal = getVal(Ty, $4);
3764 $$.I = new LoadInst(tmpVal, "", $1);
3765 $$.S.copy($3.S.get(0));
3768 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3770 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3772 error("Can't store to a nonpointer type: " +
3773 $5.PAT->get()->getDescription());
3774 const Type *ElTy = PTy->getElementType();
3775 Value *StoreVal = $3.V;
3776 Value* tmpVal = getVal(PTy, $6);
3777 if (ElTy != $3.V->getType()) {
3778 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3780 error("Can't store '" + $3.V->getType()->getDescription() +
3781 "' into space of type '" + ElTy->getDescription() + "'");
3783 PTy = PointerType::get(StoreVal->getType());
3784 if (Constant *C = dyn_cast<Constant>(tmpVal))
3785 tmpVal = ConstantExpr::getBitCast(C, PTy);
3787 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3790 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3791 $$.S.makeSignless();
3794 | GETELEMENTPTR Types ValueRef IndexList {
3796 const Type* Ty = $2.PAT->get();
3797 if (!isa<PointerType>(Ty))
3798 error("getelementptr insn requires pointer operand");
3800 std::vector<Value*> VIndices;
3801 upgradeGEPIndices(Ty, $4, VIndices);
3803 Value* tmpVal = getVal(Ty, $3);
3804 $$.I = new GetElementPtrInst(tmpVal, &VIndices[0], VIndices.size());
3805 ValueInfo VI; VI.V = tmpVal; VI.S.copy($2.S);
3806 $$.S.copy(getElementSign(VI, VIndices));
3814 int yyerror(const char *ErrorMsg) {
3816 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3817 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3818 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3819 if (yychar != YYEMPTY && yychar != 0)
3820 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3822 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3823 std::cout << "llvm-upgrade: parse failed.\n";
3827 void warning(const std::string& ErrorMsg) {
3829 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3830 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3831 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3832 if (yychar != YYEMPTY && yychar != 0)
3833 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3835 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3838 void error(const std::string& ErrorMsg, int LineNo) {
3839 if (LineNo == -1) LineNo = Upgradelineno;
3840 Upgradelineno = LineNo;
3841 yyerror(ErrorMsg.c_str());